package com.xiaochong.tir.apiservice.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.apiservice.component.hbase.CurrencyInfoHbaseComponent;
import com.xiaochong.tir.apiservice.config.hbase.HbaseConnectionFactory;
import com.xiaochong.tir.apiservice.service.*;
import com.xiaochong.tir.apiservice.util.HttpUtils;
import com.xiaochong.tir.apiservice.util.StringUtil;
import com.xiaochong.tir.common.data.hbasepo.*;
import com.xiaochong.tir.common.data.mapper.BasePeriodHistoryMapper;
import com.xiaochong.tir.common.data.mapper.CurrencyInfoMapper;
import com.xiaochong.tir.common.data.po.*;
import com.xiaochong.tir.common.data.vo.CurrencyQuotationResultVo;
import com.xiaochong.tir.common.exception.ErrorDataException;
import com.xiaochong.tir.common.exception.hbase.HbaseCloseExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseConnectionExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseGetTableExcetion;
import com.xiaochong.tir.common.util.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;

/**
 * Created by wujiaxing on 2018/4/26.
 * 各种数据计算
 */
@Component
public class CmcDataCalculateComponent {

    @Value("${tirservice.url.apiservice.makePopularityARIndexData}")
    private String tirserviceApiMakePopularityARIndexDataUrl;

    @Value("${tirservice.url.apiservice.akkaMakeIndustryToCacheOf}")
    private String akkaMakeIndustryToCacheOfUrl;

    @Value("${tirservice.url.apiservice.akkaMakeGrailIndexToCache}")
    private String akkaMakeGrailIndexToCacheUrl;

    @Value("${tirservice.url.apiservice.akkaCurrencyDiagnosisAssessment}")
    private String akkaCurrencyDiagnosisAssessmentUrl;

    @Value("${tirservice.url.apiservice.getAvgCost}")
    private String getAvgCostURL;

    @Value("${tirservice.url.apiservice.getBottomteZhi}")
    private String getBottomteZhiURL;

    @Value("${tirservice.url.apiservice.getConceptCurrency}")
    private String getConceptCurrencyURL;

    @Value("${tirservice.url.apiservice.getMarketPer}")
    private String getMarketPerURL;

    @Value("${tirservice.url.apiservice.getMonetarydiagnosisTop5}")
    private String getMonetarydiagnosisTop5URL;

    @Value("${tirservice.url.apiservice.getPressureSup}")
    private String getPressureSupURL;

    @Value("${tirservice.url.apiservice.getSpaceTrend}")
    private String getSpaceTrendURL;

    @Autowired
    private HbaseConnectionFactory hbaseConnectionFactory;

    @Autowired
    private RedisServer redisServer;

    @Autowired
    private CurrencyGlobalInfoHbaseService currencyGlobalInfoHbaseService;

    @Autowired
    private CurrencyInfoService currencyInfoService;

    @Autowired
    private CurrencyInfoHbaseService currencyInfoHbaseService;

    @Autowired
    private ConceptCategoryService conceptCategoryService;

    @Autowired
    private CurrencyConceptCategoryService currencyConceptCategoryService;

    @Autowired
    private CurrencyIndustryCategoryService currencyIndustryCategoryService;

    @Autowired
    private CurrencyIndustryMiddleService currencyIndustryMiddleService;

    @Autowired
    private BasePeriodHistoryService basePeriodHistoryService;

    @Autowired
    private HbaseBaseQueryComponent hbaseBaseQueryComponent;

    @Autowired
    private CurrencyInfoHbaseComponent currencyInfoHbaseComponent;

    @Resource
    private CoinMarketCapDataComponent coinMarketCapDataComponent;

    @Resource
    private RedisCacheComponent redisCacheComponent;

    @Autowired
    private CurrencyInfoMapper currencyInfoMapper;

    /**
     * 根据创建时间获取货币数据
     * @param rowKey
     * @return
     */
    private CmcCurrencyInfo getCmcInfosByRowKey(String rowKey){
        try {
            Map<String, Object> map = hbaseBaseQueryComponent.selectData(
                    HbaseTableUtils.CURRENCY_INFO_TABLE_NAME, rowKey);
            return JSON.parseObject(JSON.toJSONString(map), CmcCurrencyInfo.class);
        } catch (HbaseConnectionExcetion | HbaseGetTableExcetion | HbaseCloseExcetion | IOException e) {
            LogTrace.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * CmcCurrencyInfo list转map
     * @param cmcCurrencyInfos
     */
    public Map<String,CmcCurrencyInfo> cmcCurrencyInfoListToMap(List<CmcCurrencyInfo> cmcCurrencyInfos) {
        if(CollectionUtil.isBlank(cmcCurrencyInfos)){
            return null;
        }
        Map<String,CmcCurrencyInfo> map = new HashMap<>();
        for (CmcCurrencyInfo info:cmcCurrencyInfos) {
            map.put(info.getId(),info);
        }
        return map;
    }

    private Map<String,CurrencyInfo> currencyInfoListToMap(List<CurrencyInfo> currencyList) {
        if(CollectionUtil.isBlank(currencyList)){
            return null;
        }
        Map<String,CurrencyInfo> map = new HashMap<>();
        for (CurrencyInfo info:currencyList) {
            map.put(info.getCmcId(),info);
        }
        return map;
    }

    /**
     * DailyComprehensiveAnalysisInfo list转map
     *
     * @param dailyInfoList
     * @return
     */
    public Map<String,DailyComprehensiveAnalysisInfo> dailyInfoListToMap(List<DailyComprehensiveAnalysisInfo> dailyInfoList) {

        if(CollectionUtil.isBlank(dailyInfoList)){
            return null;
        }
        Map<String,DailyComprehensiveAnalysisInfo> map = new HashMap<>();
        for (DailyComprehensiveAnalysisInfo dailyInfo:dailyInfoList) {
            map.put(dailyInfo.getId(),dailyInfo);
        }
        return map;
    }


    /**
     * 计算大盘指数
     *
     * @param cmcCurrencyGlobalInfo
     * @return
     */
    public BroaderIndex calculateBroaderIndex(CmcCurrencyGlobalInfo cmcCurrencyGlobalInfo){

        try {

            //当前最最新的CMC全球数据
            CurrencyGlobalInfoHbase descRowKey =
                    currencyGlobalInfoHbaseService.selectByCreateTime("desc");
            //最早的CMC全球数据
            CurrencyGlobalInfoHbase ascRowKey =
                    currencyGlobalInfoHbaseService.selectByCreateTime("asc");
            //今日凌晨的CMC全球数据
            CurrencyGlobalInfoHbase todayRowKey =
                    currencyGlobalInfoHbaseService.selectTodayFirst();
            LogTrace.info(LogTraceKeysUtils.AKKA_DIAGNOSIS_MARKET_PERFORMANCE_INDEX_TITLE,
                    "descRowKey", descRowKey != null? JSONObject.toJSONString(descRowKey):"null");
            LogTrace.info(LogTraceKeysUtils.AKKA_DIAGNOSIS_MARKET_PERFORMANCE_INDEX_TITLE,
                    "ascRowKey", ascRowKey != null? JSONObject.toJSONString(ascRowKey):"null");
            LogTrace.info(LogTraceKeysUtils.AKKA_DIAGNOSIS_MARKET_PERFORMANCE_INDEX_TITLE,
                    "todayRowKey", todayRowKey != null? JSONObject.toJSONString(todayRowKey):"null");

            CmcCurrencyGlobalInfo laseInfo;
            if(cmcCurrencyGlobalInfo!=null){
                laseInfo = cmcCurrencyGlobalInfo;
            }else{
                Map<String, Object> lastMap = hbaseBaseQueryComponent.selectData(
                        HbaseTableUtils.CURRENCY_GLOBAL_INFO_TABLE_NAME, descRowKey.getRowKey());
                laseInfo = JSON.parseObject(JSON.toJSONString(lastMap),CmcCurrencyGlobalInfo.class);
            }


            Map<String, Object> firstMap = hbaseBaseQueryComponent.selectData(
                    HbaseTableUtils.CURRENCY_GLOBAL_INFO_TABLE_NAME, ascRowKey.getRowKey());
            CmcCurrencyGlobalInfo firstInfo = JSON.parseObject(JSON.toJSONString(firstMap),CmcCurrencyGlobalInfo.class);


            Map<String, Object> todayMap = hbaseBaseQueryComponent.selectData(
                    HbaseTableUtils.CURRENCY_GLOBAL_INFO_TABLE_NAME, todayRowKey.getRowKey());
            CmcCurrencyGlobalInfo todayInfo = JSON.parseObject(JSON.toJSONString(todayMap),CmcCurrencyGlobalInfo.class);

            //获取市值 USD
            BigDecimal lastTotalMarketCap = new BigDecimal(laseInfo.getTotalMarketCapUsd());
            BigDecimal firstTotalMarketCap = new BigDecimal(firstInfo.getTotalMarketCapUsd());
            BigDecimal todayTotalMarketCap = new BigDecimal(todayInfo.getTotalMarketCapUsd());
            BroaderIndex broaderIndex = new BroaderIndex();
            broaderIndex.setCreateTime(laseInfo.getCreateTime());
            //TIR大盘指数值 :(当前数字货币最新总市值/基期的数字货币总市值)*1000（基期：TIR网站上线那一天为基期
            broaderIndex.setBroaderIndex(
                    lastTotalMarketCap
                            .divide(firstTotalMarketCap,5,BigDecimal.ROUND_DOWN)
                            .multiply(new BigDecimal(1000))
            );
            //涨跌幅 :(当前数字货币最新总市值  —  当日0点数字货币总市值)/当日0点数字货币总市值
            broaderIndex.setBroaderRiseFall(
                    lastTotalMarketCap
                            .subtract(todayTotalMarketCap)
                            .divide(todayTotalMarketCap,4,BigDecimal.ROUND_DOWN)
            );
            //设置大盘指数缓存
            redisServer.set(RedisKeysUtils.TIR_BROADER_INDEX,JSON.toJSONString(broaderIndex));
            //设置最高大盘指数
            String highKey = RedisKeysUtils.TIR_BROADER_INDEX_HIGH+DateUtils.getCurrentDateString();
            //设置最低大盘指数
            String lowKey = RedisKeysUtils.TIR_BROADER_INDEX_LOW+DateUtils.getCurrentDateString();

            //设置过期时间
            Long TIME_EXPIRE = 1000L;

            //判断今天最高大盘
            if(redisServer.exists(highKey)){
                String hight = redisServer.get(highKey);
                if(!StringUtils.isBlank(hight)&&
                        new BigDecimal(hight).compareTo(new BigDecimal(broaderIndex.getBroaderIndex().toString()))<0){
                    redisServer.set(highKey,broaderIndex.getBroaderIndex().toString() , TIME_EXPIRE);
                }
            }else{
                redisServer.set(highKey,broaderIndex.getBroaderIndex().toString() , TIME_EXPIRE);
            }

            //判断今天最低大盘
            if(redisServer.exists(lowKey)){
                String low = redisServer.get(lowKey);
                if(!StringUtils.isBlank(low)&&
                        new BigDecimal(low).compareTo(new BigDecimal(broaderIndex.getBroaderIndex().toString()))>0){
                    redisServer.set(lowKey,broaderIndex.getBroaderIndex().toString() , TIME_EXPIRE);
                }
            }else {
                redisServer.set(lowKey,broaderIndex.getBroaderIndex().toString(),TIME_EXPIRE);
            }

            LogTrace.info(LogTraceKeysUtils.COIN_MARKET_CAP_API_SCHEDULED_TITLE, LogTraceKeysUtils.DATA,"cache");

            return broaderIndex;

        } catch (HbaseConnectionExcetion | HbaseGetTableExcetion | IOException | HbaseCloseExcetion e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(), e);
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 计算权重指数
     * @param cmcMap
     * @return
     */
    public WeightIndex calculateWeightIndex(Map<String, CmcCurrencyInfo> cmcMap) {

        try{
            BigDecimal lastWeightTotalMarketCap = new BigDecimal(0);
            BigDecimal firstWeightTotalMarketCap = this.calculateBasePeriodWeightIndex();
            BigDecimal todayWeightTotalMarketCap = new BigDecimal(0);
            List<CurrencyInfo> currencyInfos = redisCacheComponent.getWeightsCurrencyList();
            if(CollectionUtils.isEmpty(currencyInfos)){
                throw new ErrorDataException("计算权重指数获取权重信息失败！");
            }

            /*BigDecimal basePeriod = null;
            Map<String, CmcCurrencyInfo> firstCmcMap = null;
            if("0".equals(redisServer.get(RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD))){
                BasePeriodHistory basePeriodHistory = new BasePeriodHistory();
                basePeriodHistory.setBasePeriodMark(BasePeriodMarkEnum.WEIGHT_INDEX.getIndex());
                basePeriodHistory = basePeriodHistoryService.selectByEntity(basePeriodHistory);
                if(basePeriodHistory!=null && basePeriodHistory.getBasePeriod()!=null){
                    basePeriod = basePeriodHistory.getBasePeriod();
                }

            }
            if(basePeriod==null){
                Date minCreateTime = redisCacheComponent.getCurrencyInfoHbaseMinCreateTime();
                List<CmcCurrencyInfo> firstCmcInfos = coinMarketCapDataComponent.getCmcInfosByDate(minCreateTime);
                if(CollectionUtils.isEmpty(firstCmcInfos)){
                    throw new ErrorDataException("基期货币信息获取失败！");
                }
                firstCmcMap = this.cmcCurrencyInfoListToMap(firstCmcInfos);
            }*/
            //BigDecimal basePeriod = this.calculateBasePeriodWeightIndex();

            Date todayCreateTime = currencyInfoHbaseService.todayCreateTime("asc");
            Map<String, CmcCurrencyInfo> lastCmcInfoMap = null;
            if(CollectionUtil.isBlank(cmcMap)){
                Date maxCreateTime = currencyInfoHbaseService.selectMaxMinCreateTime("desc");
                List<CmcCurrencyInfo> cmcInfosByDate = coinMarketCapDataComponent.getCmcInfosByDate(maxCreateTime);
                if(CollectionUtil.isNotBlank(cmcInfosByDate)){
                    lastCmcInfoMap = this.cmcCurrencyInfoListToMap(cmcInfosByDate);
                }
            }else{
                lastCmcInfoMap =  cmcMap;
            }
            if(CollectionUtil.isBlank(lastCmcInfoMap)){
                throw new ErrorDataException("货币信息获取失败！");
            }



            List<CmcCurrencyInfo> todayCmcInfos = coinMarketCapDataComponent.getCmcInfosByDate(todayCreateTime);
            if(CollectionUtils.isEmpty(todayCmcInfos)){
                throw new ErrorDataException("今日货币信息获取失败！");
            }
            Map<String, CmcCurrencyInfo> todayCmcMap = this.cmcCurrencyInfoListToMap(todayCmcInfos);



            Date createTime = null;
            for (CurrencyInfo currencyInfo:currencyInfos) {
                try{
                    CmcCurrencyInfo cmcInfo = lastCmcInfoMap.get(currencyInfo.getCmcId());
                    if(cmcInfo!=null){
                        if(createTime==null){
                            createTime = cmcInfo.getCreateTime();
                        }
                        BigDecimal price = new BigDecimal(cmcInfo.getPriceCny());
                        BigDecimal availableSupply = new BigDecimal(cmcInfo.getAvailableSupply());
                        lastWeightTotalMarketCap =
                                lastWeightTotalMarketCap.add(price.multiply(availableSupply));
                    }

                    /*if(basePeriod==null){
                        cmcInfo = firstCmcMap.get(currencyInfo.getCmcId());
                        if(cmcInfo!=null){
                            BigDecimal price = new BigDecimal(cmcInfo.getPriceCny());
                            BigDecimal availableSupply = new BigDecimal(cmcInfo.getAvailableSupply());
                            firstWeightTotalMarketCap =
                                    firstWeightTotalMarketCap.add(price.multiply(availableSupply));
                        }
                    }else if(firstWeightTotalMarketCap.doubleValue()==0){
                        firstWeightTotalMarketCap = basePeriod;
                    }*/

                    cmcInfo = todayCmcMap.get(currencyInfo.getCmcId());
                    if(cmcInfo!=null){
                        BigDecimal price = new BigDecimal(cmcInfo.getPriceCny());
                        BigDecimal availableSupply = new BigDecimal(cmcInfo.getAvailableSupply());
                        todayWeightTotalMarketCap =
                                todayWeightTotalMarketCap.add(price.multiply(availableSupply));
                    }

                }catch (Exception e) {
                    e.printStackTrace();
                    LogTrace.error(e.getMessage(),e);
                }


            }

            /*if(basePeriod==null){
                BasePeriodHistory basePeriodHistory = new BasePeriodHistory();
                basePeriodHistory.setBasePeriodMark(BasePeriodMarkEnum.WEIGHT_INDEX.getIndex());
                basePeriodHistory.setBasePeriod(firstWeightTotalMarketCap);
                basePeriodHistoryService.insertSelective(basePeriodHistory);
                redisServer.set(RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD,"0");
            }*/


            WeightIndex weightIndex = new WeightIndex();
            weightIndex.setCreateTime(createTime);
            if(firstWeightTotalMarketCap!=null && firstWeightTotalMarketCap.intValue()!=0){
                weightIndex.setWeightIndex(
                        lastWeightTotalMarketCap
                                .divide(firstWeightTotalMarketCap,5,BigDecimal.ROUND_DOWN)
                                .multiply(new BigDecimal(1000))
                );
            }
            if(todayWeightTotalMarketCap.intValue()!=0){
                weightIndex.setWeightRiseFall(
                        lastWeightTotalMarketCap
                                .subtract(todayWeightTotalMarketCap)
                                .divide(todayWeightTotalMarketCap,4,BigDecimal.ROUND_DOWN)
                );
            }
            redisServer.set(RedisKeysUtils.TIR_WEIGHT_INDEX,JSON.toJSONString(weightIndex));

            return weightIndex;
        }catch (Exception e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(),e);
        }
        return null;

    }


    /**
     * 计算各行业指数
     *
     * @param allCmcInfos
     * @return
     */
    public List<IndustryIndex> calculateIndustryIndex(List<CmcCurrencyInfo> allCmcInfos) {
        if(allCmcInfos==null || allCmcInfos.size()==0){
            Date maxCreateTime = currencyInfoHbaseService.selectMaxMinCreateTime("desc");
            allCmcInfos = coinMarketCapDataComponent.getCmcInfosByDate(maxCreateTime);
        }


        Date todayCreateTime = currencyInfoHbaseService.todayCreateTime("asc");
        List<CmcCurrencyInfo> todayCmcInfos = coinMarketCapDataComponent.getCmcInfosByDate(todayCreateTime);

        CurrencyIndustryCategory searchCurrencyIndustryCategory = new CurrencyIndustryCategory();
        searchCurrencyIndustryCategory.setParentId(0);
        searchCurrencyIndustryCategory.setEnableFlag(true);
        List<CurrencyIndustryCategory> parentIndustryCategories =
                currencyIndustryCategoryService.selectByEntityList(searchCurrencyIndustryCategory);
        List<IndustryIndex> industryIndices = new ArrayList<>();
        for (CurrencyIndustryCategory parentIndustryCategory:parentIndustryCategories) {
            BigDecimal lastSum = this.sumIndustryPrice(parentIndustryCategory, allCmcInfos);
            BigDecimal firstSum = this.calculateBasePeriodindustry(parentIndustryCategory);
            BigDecimal todaySum = this.sumIndustryPrice(parentIndustryCategory, todayCmcInfos);
            if(     firstSum==null || todaySum==null
                    || firstSum.doubleValue()==0 || todaySum.doubleValue()==0){
                continue;
            }
            IndustryIndex industryIndex = new IndustryIndex();
            industryIndex.setCurrencyIndustryCategoryId(parentIndustryCategory.getId());
            industryIndex.setCreateTime(allCmcInfos.get(0).getCreateTime());
            industryIndex.setIndustryIndex(
                    lastSum.divide(firstSum,5,BigDecimal.ROUND_DOWN)
                            .multiply(new BigDecimal(1000))
            );
            industryIndex.setIndustryRiseFall(
                    lastSum.subtract(todaySum)
                            .divide(todaySum,4,BigDecimal.ROUND_DOWN)
            );
            redisServer.set(RedisKeysUtils.TIR_INDUSTRY_INDEX+parentIndustryCategory.getId(),JSON.toJSONString(industryIndex));
            industryIndices.add(industryIndex);
        }


        return industryIndices;
    }


    /**
     * 计算行业流通市值
     *
     * @param parentIndustryCategory
     * @param allCmcInfos
     * @return
     */
    private BigDecimal sumIndustryPrice(CurrencyIndustryCategory parentIndustryCategory,List<CmcCurrencyInfo> allCmcInfos){
        BigDecimal sumIndustrymMarketCap = new BigDecimal(0);
        List<CurrencyIndustryCategory> all = currencyIndustryCategoryService.selectByEntityList(new CurrencyIndustryCategory());
        List<CurrencyIndustryCategory> currencyIndustryCategories =
                this.searchAllSonCurrencyIndustryCategory(parentIndustryCategory,all);
        if(currencyIndustryCategories==null || currencyIndustryCategories.size()==0){
            return sumIndustrymMarketCap;
        }
        for (CurrencyIndustryCategory currencyIndustryCategory: currencyIndustryCategories) {
            CurrencyIndustryMiddle searchMiddle = new CurrencyIndustryMiddle();
            searchMiddle.setIndustryCategoryId(currencyIndustryCategory.getId());
            List<CurrencyIndustryMiddle> currencyIndustryMiddles = currencyIndustryMiddleService.selectByEntityList(searchMiddle);
            for (CurrencyIndustryMiddle currencyIndustryMiddle:currencyIndustryMiddles) {
                CurrencyInfo currencyInfo = new CurrencyInfo();
                currencyInfo.setId(currencyIndustryMiddle.getCurrencyId());
                currencyInfo = currencyInfoService.selectByEntity(currencyInfo);
                if(currencyInfo==null || StringUtils.isBlank(currencyInfo.getCmcId())){
                    continue;
                }
                for (CmcCurrencyInfo cmcCurrencyInfo:allCmcInfos) {
                    if(currencyInfo.getCmcId().equals(cmcCurrencyInfo.getId())){
                        if(MathUtils.isNumeric(cmcCurrencyInfo.getPriceUsd())){
                            sumIndustrymMarketCap = sumIndustrymMarketCap.add(new BigDecimal(cmcCurrencyInfo.getPriceUsd()));
                        }
                        break;
                    }
                }
            }
        }

        return sumIndustrymMarketCap;
    }

    /**
     * 递归查找所有子行业
     *
     * @param parentIndustryCategory
     * @param all
     * @return
     */
    private List<CurrencyIndustryCategory> searchAllSonCurrencyIndustryCategory(CurrencyIndustryCategory parentIndustryCategory
            , List<CurrencyIndustryCategory> all) {
        List<CurrencyIndustryCategory> resultList = new ArrayList<>();
        resultList.add(parentIndustryCategory);
        List<CurrencyIndustryCategory> currencyIndustryCategories = new ArrayList<>();
        for (int i = 0; i < all.size(); i++) {
            CurrencyIndustryCategory category = all.get(i);
            if(category.getId().equals(parentIndustryCategory.getId())){
                all.remove(i);
                i--;
            }else if(category.getParentId().equals(parentIndustryCategory.getId())){
                currencyIndustryCategories.add(category);
                all.remove(i);
                i--;
            }
        }
        if(currencyIndustryCategories.size()==0){
            return resultList;
        }
        for (CurrencyIndustryCategory currencyIndustryCategory:currencyIndustryCategories) {
            resultList.add(currencyIndustryCategory);
            List<CurrencyIndustryCategory> son = this.searchAllSonCurrencyIndustryCategory(currencyIndustryCategory, all);
            if(son==null || son.size()==0){
                continue;
            }
            resultList.addAll(son);
        }
        return resultList;
    }

    /**
     * 计算权重流通市值
     *
     * @return
     */
    public BigDecimal weightMarketCap() {
        if(1!=currencyInfoHbaseService.todayCreateTimeCount()){
            return null;
        }

        BigDecimal lastWeightTotalMarketCap = new BigDecimal(0);
        List<CurrencyInfo> currencyConfigs = redisCacheComponent.getWeightsCurrencyList();
        Date todayCreateTime = currencyInfoHbaseService.todayCreateTime("asc");
        List<CmcCurrencyInfo> todayCmcInfos = coinMarketCapDataComponent.getCmcInfosByDate(todayCreateTime);
        if(CollectionUtil.isBlank(todayCmcInfos)){
            LogTrace.info("计算权重流通市值","计算权重流通市值","获取cmc数据失败！");
            LogTrace.info("计算权重流通市值","todayCreateTime",String.valueOf(todayCreateTime));
            return null;
        }
        Map<String, CmcCurrencyInfo> infoMap = this.cmcCurrencyInfoListToMap(todayCmcInfos);
        for (CurrencyInfo cConfig:currencyConfigs) {
            CmcCurrencyInfo cmcInfo = infoMap.get(cConfig.getCmcId());
            if(cmcInfo==null){
                continue;
            }
            BigDecimal priceUsd = new BigDecimal(cmcInfo.getPriceUsd());
            BigDecimal availableSupply = new BigDecimal(cmcInfo.getAvailableSupply());
            lastWeightTotalMarketCap =
                    lastWeightTotalMarketCap.add(priceUsd.multiply(availableSupply));
        }
        redisServer.set(RedisKeysUtils.TIR_WEIGHT_SUPPLY_PRICE,lastWeightTotalMarketCap.toString());
        return lastWeightTotalMarketCap;
    }

    /**
     * 概念指数计算
     * @param cmcInfoMap
     * @return
     */
    public List<ConceptIndex> calculateConceptIndex(Map<String, CmcCurrencyInfo> cmcInfoMap) {

        List<CmcCurrencyInfo> allCmcInfos = new ArrayList<>();
        List<CurrencyInfo> currencyList = redisCacheComponent.getCurrencyList();
        //Date minCreateTime = redisCacheComponent.getCurrencyInfoHbaseMinCreateTime();
        //List<CmcCurrencyInfo> allMinCmcInfos = coinMarketCapDataComponent.getCmcInfosByDate(minCreateTime);
       // Map<String, CmcCurrencyInfo> allMinCmcInfoMap = this.cmcCurrencyInfoListToMap(allMinCmcInfos);
        //List<CmcCurrencyInfo> minCmcInfos = new ArrayList<>();
        for (CurrencyInfo currencyInfo:currencyList) {
            CmcCurrencyInfo nowInfo = cmcInfoMap.get(currencyInfo.getCmcId());
            if(nowInfo!=null){
                allCmcInfos.add(nowInfo);
            }
            /*CmcCurrencyInfo minInfo = allMinCmcInfoMap.get(currencyInfo.getCmcId());
            if(minInfo!=null){
                minCmcInfos.add(minInfo);
            }*/
        }

        ConceptCategory searchConceptCategory = new ConceptCategory();
        searchConceptCategory.setEnableFlag(true);
        List<ConceptCategory> conceptCategories = conceptCategoryService.selectByEntityList(searchConceptCategory);


        List<ConceptIndex> conceptIndices = new ArrayList<>();
        for (ConceptCategory conceptCategory:conceptCategories) {
            BigDecimal lastSum = new BigDecimal(0);
            BigDecimal firstSum = new BigDecimal(0);
            BigDecimal lastSumVolume24hCnyPrice = new BigDecimal(0);
            BigDecimal lastSumPercentChange24h = new BigDecimal(0);
            List<CmcCurrencyInfo> lastCmcInfos =
                    this.conceptCurrency(conceptCategory, allCmcInfos);

            ConceptIndex conceptIndex = new ConceptIndex();
            conceptIndex.setConceptCategoryId(conceptCategory.getId());
            conceptIndex.setCreateTime(allCmcInfos.get(0).getCreateTime());
            if(CollectionUtils.isNotEmpty(lastCmcInfos)){
                lastCmcInfos.sort((c1,c2)->{
                    if (MathUtils.isNotNumeric(c1.getMarketCapCny())
                            && MathUtils.isNotNumeric(c2.getMarketCapCny())) {
                        return 0;
                    } else if (MathUtils.isNotNumeric(c1.getMarketCapCny())) {
                        return 1;
                    } else if (MathUtils.isNotNumeric(c2.getMarketCapCny())) {
                        return -1;
                    }
                    BigDecimal c1BigDecimal = new BigDecimal(c1.getMarketCapCny());
                    BigDecimal c2BigDecimal = new BigDecimal(c2.getMarketCapCny());
                    return c2BigDecimal.compareTo(c1BigDecimal);
                });

                CmcCurrencyInfo maxInfo = lastCmcInfos.get(0);
                CmcCurrencyInfo minInfo = lastCmcInfos.get(0);
                int riseCount = 0;
                int fallCount = 0;
                for (CmcCurrencyInfo last:lastCmcInfos) {
                    if(MathUtils.isNotNumeric(last.getMarketCapCny()) || MathUtils.isNotNumeric(last.getVolume24hCny())){
                        continue;
                    }
                    lastSum = lastSum.add(new BigDecimal(last.getMarketCapCny()));
                    lastSumVolume24hCnyPrice = lastSumVolume24hCnyPrice.add(
                            new BigDecimal(last.getVolume24hCny()) );
                    if(StringUtils.isBlank(last.getPercentChange24h()) || last.getPercentChange24h().equals("null")){
                        continue;
                    }
                    BigDecimal percentChange24h = new BigDecimal(last.getPercentChange24h());
                    lastSumPercentChange24h = lastSumPercentChange24h.add(percentChange24h);
                    if(percentChange24h.doubleValue()>0){
                        riseCount++;
                    }
                    if(percentChange24h.doubleValue()<0){
                        fallCount++;
                    }
                    if(percentChange24h.doubleValue()>
                            new BigDecimal(maxInfo.getPercentChange24h()).doubleValue()){
                        maxInfo = last;
                    }
                    if(percentChange24h.doubleValue()<
                            new BigDecimal(minInfo.getPercentChange24h()).doubleValue()){
                        minInfo = last;
                    }

                }


                firstSum =
                        redisCacheComponent.getConceptBasePeriodSumMarket(conceptCategory.getId());

                if(firstSum!=null && !"0".equals(redisServer.get(RedisKeysUtils.CURRCY_NOTION_BASE_PERIOD+conceptCategory.getId())) ){
                    redisServer.set(RedisKeysUtils.CONCEPT_BASE_PERIOD_SUM_MARKET+conceptCategory.getId(),firstSum.doubleValue());
                    redisServer.set(RedisKeysUtils.CURRCY_NOTION_BASE_PERIOD+conceptCategory.getId(),0);
                }

                if(firstSum!=null && firstSum.intValue()!=0){
                    conceptIndex.setConceptIndex(
                            lastSum.divide(firstSum,5,BigDecimal.ROUND_DOWN)
                                    .multiply( new BigDecimal(1000)).setScale( 2,BigDecimal.ROUND_DOWN )
                    );
                }
                conceptIndex.setSumVolume24hCnyPrice(lastSumVolume24hCnyPrice);
                if(lastCmcInfos.size()!=0){
                    conceptIndex.setAvgPercentChange24h(lastSumPercentChange24h
                            .divide(new BigDecimal(lastCmcInfos.size()),2,BigDecimal.ROUND_DOWN));
                }
                conceptIndex.setMaxPercentChange24hInfo(maxInfo);
                conceptIndex.setMinPercentChange24hInfo(minInfo);
                conceptIndex.setCount(lastCmcInfos.size());
                conceptIndex.setRiseCount(riseCount);
                conceptIndex.setFallCount(fallCount);
                conceptIndex.setConceptCategoryName( conceptCategory.getConceptCategoryName() );
                conceptIndices.add(conceptIndex);
                //redisServer.set(RedisKeysUtils.TIR_CONCEPT_CURRENCY_RANK+conceptCategory.getId(),JSON.toJSONString(lastCmcInfos));
                currencyInfoHbaseComponent.saveConceptualQuotesDetail(conceptCategory,lastCmcInfos);
            }else{
                conceptIndex.setRiseCount(0);
                conceptIndex.setFallCount(0);
                conceptIndex.setCount(0);
                conceptIndex.setAvgPercentChange24h(new BigDecimal(0));
                conceptIndex.setSumVolume24hCnyPrice(new BigDecimal(0));
            }
            redisServer.set(RedisKeysUtils.TIR_CONCEPT_INDEX+conceptCategory.getId(),JSON.toJSONString(conceptIndex));

        }
        return conceptIndices;
    }

    /**
     * 保存概念指数相关数据
     *
     * @param conceptIndices
     */
    public void saveConceptIndex(List<ConceptIndex> conceptIndices) {
        Date dateTime;
        if(conceptIndices.get(0).getCreateTime()!=null){
            dateTime = conceptIndices.get(0).getCreateTime();
        }else{dateTime = new Date();}
        JSONObject mainObject;
        mainObject = new JSONObject();
        for (ConceptIndex conceptIndex:conceptIndices) {
            String key = conceptIndex.getConceptCategoryId()+"";
            mainObject.put(key,conceptIndex);
        }
        currencyInfoHbaseComponent.insertHbaseString(HbaseTableUtils.DAILY_CONCEPTUAL_INDEX_INFO_TABLE_NAME
                ,DateUtils.dateFormatString(dateTime,DateUtils.format_ymds)
                ,HbaseTableUtils.DAILY_CONCEPTUAL_INDEX_INFO_TABLE_FAMILY
                ,HbaseTableUtils.DAILY_CONCEPTUAL_INDEX_INFO_QUALIFIER
                ,mainObject.toJSONString());




        for (ConceptIndex conceptIndex:conceptIndices) {
            try{
                String data = hbaseBaseQueryComponent.selectByQualifierData(
                        HbaseTableUtils.CONCEPTUAL_QUOTES_TABLE_NAME
                        , HbaseTableUtils.CONCEPTUAL_QUOTES_TABLE_NAME_FAMILY
                        , HbaseTableUtils.CONCEPTUAL_QUOTES_TABLE_NAME_QUALIFIER
                        , conceptIndex.getConceptCategoryId()+"@"+DateUtils.getCurrentDateString());
                if(StringUtils.isBlank(data)){
                    mainObject = new JSONObject();
                }else{
                    mainObject = JSON.parseObject(data);
                }

                String key = DateUtils.dateToLocalDateTime(conceptIndex.getCreateTime()).getHour()+"";
                JSONArray jsonArray = mainObject.getJSONArray(key);
                if(CollectionUtil.isBlank(jsonArray)){
                    jsonArray = new JSONArray();
                }
                jsonArray.add(conceptIndex);
                mainObject.put(key,jsonArray);

                currencyInfoHbaseComponent.insertHbaseString(HbaseTableUtils.CONCEPTUAL_QUOTES_TABLE_NAME
                        ,conceptIndex.getConceptCategoryId()+"@"+DateUtils.getCurrentDateString()
                        ,HbaseTableUtils.CONCEPTUAL_QUOTES_TABLE_NAME_FAMILY
                        ,HbaseTableUtils.CONCEPTUAL_QUOTES_TABLE_NAME_QUALIFIER
                        ,mainObject.toJSONString());
            }catch (Exception e){
                e.printStackTrace();
                LogTrace.error(e.getMessage(),e);
            }

        }

        try {
            HttpUtils.getAkka(getBottomteZhiURL);
            HttpUtils.getAkka(getConceptCurrencyURL);
        }catch (Exception e){
            e.printStackTrace();
            LogTrace.error(e.getMessage(),e);
        }


    }

    /**
     * 概念下货币统计
     * @param conceptCategory
     * @param allCmcInfos
     * @return
     */
    private List<CmcCurrencyInfo> conceptCurrency(ConceptCategory conceptCategory,
                                                  List<CmcCurrencyInfo> allCmcInfos) {
        CurrencyConceptCategory searchCurrencyConceptCategory = new CurrencyConceptCategory();
        searchCurrencyConceptCategory.setConceptCategory(conceptCategory.getId());
        List<CurrencyConceptCategory> currencyConceptCategories =
                currencyConceptCategoryService.selectByEntityList(searchCurrencyConceptCategory);
        Map<String, CmcCurrencyInfo> infoMap = this.cmcCurrencyInfoListToMap(allCmcInfos);
        String jsonString = redisServer.get(RedisKeysUtils.TIR_CONCEPT_CURRENCY_RANK + conceptCategory.getId());
        Map<String, CmcCurrencyInfo> redisinfoMap = null;
        if(StringUtils.isNoneBlank(jsonString)){
            List<CmcCurrencyInfo> redisInfos = JSON.parseArray(jsonString, CmcCurrencyInfo.class);
            redisinfoMap = this.cmcCurrencyInfoListToMap(redisInfos);
        }
        List<CmcCurrencyInfo> list = new ArrayList<>();
        for (CurrencyConceptCategory currencyConceptCategory:currencyConceptCategories) {
            CurrencyInfo currencyInfo = new CurrencyInfo();
            currencyInfo.setId(currencyConceptCategory.getCurrencyId());
            currencyInfo = currencyInfoService.selectByEntity(currencyInfo);
            if(currencyInfo==null || StringUtils.isBlank(currencyInfo.getCmcId())){
                continue;
            }
            CmcCurrencyInfo cmcCurrencyInfo = infoMap.get(currencyInfo.getCmcId());
            if(cmcCurrencyInfo!=null){
                list.add(cmcCurrencyInfo);
            }else if(CollectionUtil.isNotBlank(redisinfoMap)){
                CmcCurrencyInfo info = redisinfoMap.get(currencyInfo.getCmcId());
                if(null != info){
                    list.add(info);
                }
            }
        }
        redisServer.set(RedisKeysUtils.TIR_CONCEPT_CURRENCY_RANK+conceptCategory.getId(),JSON.toJSONString(list));

        return list;
    }


    /**
     * 获取概念市值
     *
     * @param conceptCategory
     * @param allCmcInfos
     * @return
     */
    private BigDecimal sumConceptPrice(ConceptCategory conceptCategory, List<CmcCurrencyInfo> allCmcInfos) {
        BigDecimal sumConceptMarketCap = new BigDecimal(0);
        CurrencyConceptCategory searchCurrencyConceptCategory = new CurrencyConceptCategory();
        searchCurrencyConceptCategory.setConceptCategory(conceptCategory.getId());
        List<CurrencyConceptCategory> currencyConceptCategories =
                currencyConceptCategoryService.selectByEntityList(searchCurrencyConceptCategory);
        Map<String, CmcCurrencyInfo> infoMap = this.cmcCurrencyInfoListToMap(allCmcInfos);
        for (CurrencyConceptCategory currencyConceptCategory:currencyConceptCategories) {
            CurrencyInfo currencyInfo = new CurrencyInfo();
            currencyInfo.setId(currencyConceptCategory.getCurrencyId());
            currencyInfo = currencyInfoService.selectByEntity(currencyInfo);
            if(currencyInfo==null || StringUtils.isBlank(currencyInfo.getCmcId())){
                continue;
            }
            CmcCurrencyInfo cmcCurrencyInfo = infoMap.get(currencyInfo.getCmcId());
            if(cmcCurrencyInfo!=null){
                sumConceptMarketCap = sumConceptMarketCap.add(new BigDecimal(cmcCurrencyInfo.getPriceUsd()));
            }
        }
        return sumConceptMarketCap;
    }


    /**
     * 获取行业流通市值
     * @return
     */
    public List<SumIndustrySupplyPrice> sumIndustrySupplyPrice() {
        if(1!=currencyInfoHbaseService.todayCreateTimeCount()){
            return null;
        }
        CurrencyIndustryCategory search = new CurrencyIndustryCategory();
        search.setParentId(0);
        List<CurrencyIndustryCategory> currencyIndustryCategories =
                currencyIndustryCategoryService.selectByEntityList(search);
        if(currencyIndustryCategories==null || currencyIndustryCategories.size()==0){
            return null;
        }
        List<SumIndustrySupplyPrice> sumIndustrySupplyPrices = new ArrayList<>();
        Date todayCreateTime = currencyInfoHbaseService.todayCreateTime("asc");
        List<CmcCurrencyInfo> todayCmcInfos = coinMarketCapDataComponent.getCmcInfosByDate(todayCreateTime);
        for (CurrencyIndustryCategory currencyIndustryCategory:currencyIndustryCategories) {
            SumIndustrySupplyPrice sumIndustrySupplyPrice = new SumIndustrySupplyPrice();
            sumIndustrySupplyPrice.setCurrencyIndustryCategoryId(currencyIndustryCategory.getId());
            sumIndustrySupplyPrice.setSumIndustrySupplyPrice(this.sumIndustryPrice(currencyIndustryCategory, todayCmcInfos));
            sumIndustrySupplyPrice.setCreateTime(currencyIndustryCategories.get(0).getCreateTime());
            sumIndustrySupplyPrices.add(sumIndustrySupplyPrice);
            redisServer.set(RedisKeysUtils.SUM_INDUSTRY_SUPPLY_PRICE+currencyIndustryCategory.getId()
                    ,JSON.toJSONString(sumIndustrySupplyPrices));
        }
        return sumIndustrySupplyPrices;
    }


    /**
     * 根据涨幅排名
     * @param dateTime
     * @param currencyList
     * @param size
     * @return
     */
    private List<DailyComprehensiveAnalysisInfo> getPercentChangeRank(LocalDateTime dateTime, List<CurrencyInfo> currencyList, int size) {
        List<DailyComprehensiveAnalysisInfo> dailyListRank = new ArrayList<>();
        for (CurrencyInfo currencyInfo:currencyList) {
            Map<String, List<DailyComprehensiveAnalysisInfo>> dailyMap =
                    coinMarketCapDataComponent.getDailyCurrencyInfor(
                            currencyInfo.getCmcId()+"@"+ DateUtils.localDateTimeFormatString(
                                    dateTime,DateUtils.format_ymds));
            if(CollectionUtil.isNotBlank(dailyMap)){
                DailyComprehensiveAnalysisInfo info = DailyInfoUtils.getNearDailyInfo(dailyMap,8,0);
                if(info!=null){
                    if(dailyListRank.size()==0){

                        dailyListRank.add(info);
                    }else if(dailyListRank.size()<size){
                        DailyComprehensiveAnalysisInfo max = dailyListRank.get(0);
                        if(MathUtils.isNumeric(max.getPercentChange24h()) && MathUtils.isNumeric(info.getPercentChange24h())){
                            BigDecimal maxChange = new BigDecimal(max.getPercentChange24h());
                            BigDecimal todayChange = new BigDecimal(info.getPercentChange24h());
                            if(todayChange.doubleValue()>maxChange.doubleValue()){
                                dailyListRank.add(0,info);
                            }else{
                                dailyListRank.add(info);
                            }
                        }
                    }else{
                        DailyComprehensiveAnalysisInfo max = dailyListRank.get(0);
                        if(MathUtils.isNumeric(max.getPercentChange24h()) && MathUtils.isNumeric(info.getPercentChange24h())){
                            BigDecimal maxChange = new BigDecimal(max.getPercentChange24h());
                            BigDecimal todayChange = new BigDecimal(info.getPercentChange24h());
                            if(todayChange.doubleValue()>maxChange.doubleValue()){
                                dailyListRank.add(0,info);
                                dailyListRank.remove(size);
                            }
                        }
                    }
                }
            }
        }
        return dailyListRank;

    }

    /**
     * 平均涨幅
     * @param dailyListRank
     * @param currencyInfoMap
     * @return
     */
    private BigDecimal getAvgChangeRankPrice(List<DailyComprehensiveAnalysisInfo> dailyListRank, Map<String, CurrencyInfo> currencyInfoMap) {
        BigDecimal avgPrice = new BigDecimal(0);
        for (DailyComprehensiveAnalysisInfo info:dailyListRank) {
            CurrencyInfo currencyInfo = currencyInfoMap.get(info.getId());
            if(MathUtils.isNotNumeric(info.getPriceCny()) || currencyInfo==null || currencyInfo.getFixedWeights()==null){
                continue;
            }
            BigDecimal price = new BigDecimal(info.getPriceCny());
            avgPrice = avgPrice.add(price.multiply(currencyInfo.getFixedWeights()));
        }
        return avgPrice;
    }

    /**
     * 赚钱效益
     * @param dailyInfoMap
     * @return
     */
    public MoneyEffect calculateMoneyEffect(Map<String, DailyComprehensiveAnalysisInfo> dailyInfoMap){

        try {
            Date createTime = null;
            for (String key:dailyInfoMap.keySet()) {
                createTime = dailyInfoMap.get(key).getCreateTime();
                if(createTime!=null){break;}
            }
            LocalDateTime dateTime = DateUtils.dateToLocalDateTime(createTime);
            List<CurrencyInfo> currencyList = redisCacheComponent.getCurrencyList();
            if(currencyList==null){
                throw new ErrorDataException("缓存货币配置信息获取失败！");
            }
            Map<String,CurrencyInfo> currencyInfoMap = this.currencyInfoListToMap(currencyList);
            List<DailyComprehensiveAnalysisInfo> dailyListRank;
            if(dateTime.getHour()<8){
                dailyListRank = this.getPercentChangeRank(dateTime.minusDays(1),currencyList,10);
            }else{
                dailyListRank = this.getPercentChangeRank(dateTime,currencyList,10);
            }
            if(CollectionUtil.isBlank(dailyListRank)){
                throw new ErrorDataException("每日货币信息排名获取失败！");
            }
            List<DailyComprehensiveAnalysisInfo> todayDailyListRank = new ArrayList<>();
            List<DailyComprehensiveAnalysisInfo> yesterdayDailyListRank = new ArrayList<>();

            for (DailyComprehensiveAnalysisInfo info:dailyListRank) {
                DailyComprehensiveAnalysisInfo todayDaily = dailyInfoMap.get(info.getId());
                if(todayDaily!=null){
                    todayDailyListRank.add(todayDaily);
                }

                Map<String, List<DailyComprehensiveAnalysisInfo>> yesterdayDailyMap =
                        coinMarketCapDataComponent.getDailyCurrencyInfor(
                                info.getId()+"@"+ DateUtils.localDateTimeFormatString(
                                        dateTime.minusDays(1),DateUtils.format_ymds));
                if(CollectionUtil.isNotBlank(yesterdayDailyMap)){
                    DailyComprehensiveAnalysisInfo yesterdayDaily = DailyInfoUtils.getNearDailyInfo(
                            yesterdayDailyMap,dateTime.getHour(),dateTime.getMinute());
                    yesterdayDailyListRank.add(yesterdayDaily);
                }

            }

            BigDecimal avgPriceToday = this.getAvgChangeRankPrice(todayDailyListRank,currencyInfoMap);
            BigDecimal avgPriceYesterday = this.getAvgChangeRankPrice(yesterdayDailyListRank,currencyInfoMap);

            MoneyEffect moneyEffect = new MoneyEffect();
            if(avgPriceYesterday.doubleValue()!=0){
                Integer score = null;
                String comment = null;
                BigDecimal performance =  avgPriceToday.subtract(avgPriceYesterday)
                        .divide(avgPriceYesterday,4,BigDecimal.ROUND_DOWN);
                if(performance.doubleValue()<-0.06){
                    score = 1;
                    comment = "热点资金出逃明显";
                }else if(-0.06<=performance.doubleValue()&&performance.doubleValue()<-0.045){
                    score = 2;
                    comment = "热点资金出逃明显";
                }else if(-0.045<=performance.doubleValue()&&performance.doubleValue()<-0.03){
                    score = 3;
                    comment = "热点资金开始出逃";
                }else if(-0.03<=performance.doubleValue()&&performance.doubleValue()<-0.015){
                    score = 4;
                    comment = "热点资金开始出逃";
                }else if(-0.015<=performance.doubleValue()&&performance.doubleValue()<0){
                    score = 5;
                    comment = "热点资金炒作不明显";
                }else if(0<=performance.doubleValue()&&performance.doubleValue()<0.015){
                    score = 6;
                    comment = "热点资金炒作不明显";
                }else if(0.015<=performance.doubleValue()&&performance.doubleValue()<0.03){
                    score = 7;
                    comment = "热点资金开始炒作";
                }else if(0.03<=performance.doubleValue()&&performance.doubleValue()<0.045){
                    score = 8;
                    comment = "热点资金开始炒作";
                }else if(0.045<=performance.doubleValue()&&performance.doubleValue()<0.06){
                    score = 9;
                    comment = "热点资金炒作明显";
                }else if(0.06<=performance.doubleValue()){
                    score = 10;
                    comment = "热点资金炒作明显";
                }

                moneyEffect.setPerformance(performance);
                moneyEffect.setScore(score);
                moneyEffect.setComment(comment);
            }

            moneyEffect.setCreateTime(DateUtils.localDateTimeToDate(dateTime));


            return moneyEffect;
        } catch (Exception e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(),e);
        }
        return null;
    }




    /**
     * 保存计算信息到hbase
     * @param tableName
     * @param rowKey
     * @param family
     * @param qualifier
     * @param object
     */
    private void insertPerformance(String tableName,String rowKey,String family,String qualifier ,Object object) {
        String data = null;
        try {
            data = hbaseBaseQueryComponent.selectByQualifierData(tableName
                    , family
                    , qualifier
                    , rowKey);
        } catch (HbaseConnectionExcetion | HbaseGetTableExcetion | HbaseCloseExcetion | IOException e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(),e);
        }
        JSONObject mainObject;
        if(StringUtils.isBlank(data)){
            mainObject = new JSONObject();
        }else{
            mainObject = JSON.parseObject(data);
            //mainObject = new JSONObject();
        }
        String key = LocalDateTime.now().getHour()+"";
        JSONArray jsonArray = mainObject.getJSONArray(key);
        if(jsonArray==null){
            jsonArray = new JSONArray();
        }
        jsonArray.add(object);
        mainObject.put(key,jsonArray);
        currencyInfoHbaseComponent.insertHbaseString(tableName
                ,rowKey
                ,family
                ,qualifier
                ,mainObject.toJSONString());
    }

    /*private Map<String,List<DailyComprehensiveAnalysisInfo>> getDailyComprehensiveAnalysisInfo(String currentDateString) {
        Map<String,List<DailyComprehensiveAnalysisInfo>> map = new HashMap<>();
        try {
            String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_NAME
                    , HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_FAMILY
                    , HbaseTableUtils.DAILY_CURRENCY_INFOR_TABLE_QUALIFIER
                    , currentDateString);
            JSONObject mainObject;
            if(StringUtils.isBlank(data)){
                return null;
            }
            mainObject = JSON.parseObject(data);
            for (String key:mainObject.keySet()) {
                map.put(key,mainObject.getJSONArray(key).toJavaList(DailyComprehensiveAnalysisInfo.class));
            }

        } catch (HbaseConnectionExcetion | HbaseGetTableExcetion | HbaseCloseExcetion | IOException e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(),e);
        }
        return map;
    }*/


    /**
     * 计算权重表现
     *
     * @param dailyInfoList
     * @return
     */
    public WeightsPerformance calculateWeightsPerformance(List<DailyComprehensiveAnalysisInfo> dailyInfoList) {
        /*Map<String, List<DailyComprehensiveAnalysisInfo>> dailyMap
                = coinMarketCapDataComponent.getDailyCurrencyInfor(DateUtils.getCurrentDateString());
        if(dailyMap==null){
            return null;
        }*/
        Map<String, DailyComprehensiveAnalysisInfo> nowDailyInfoMap = this.dailyInfoListToMap(dailyInfoList);
        if(CollectionUtil.isBlank(nowDailyInfoMap)){return null;}
        //BigDecimal sumPriceMarketCapUsdNow = new BigDecimal(0);
        //BigDecimal sumMarketCapUsdNow = new BigDecimal(0);
        //BigDecimal sumPriceMarketCapUsdBefore = new BigDecimal(0);
        //BigDecimal sumMarketCapUsdBefore = new BigDecimal(0);

        List<CurrencyInfo> weightInfos = redisCacheComponent.getWeightsCurrencyList();
        BigDecimal avgPriceUsdNow = new BigDecimal(0);
        BigDecimal avgPriceUsdBefore = new BigDecimal(0);
        Date createTime = dailyInfoList.get(0).getCreateTime();
        LocalDateTime dateTime = DateUtils.dateToLocalDateTime(createTime);
        for (CurrencyInfo weightInfo:weightInfos) {
            Map<String, List<DailyComprehensiveAnalysisInfo>> dailyCurrencyInfor =
                    coinMarketCapDataComponent.getDailyCurrencyInfor(
                            weightInfo.getCmcId()+"@"
                                    +DateUtils.localDateTimeFormatString(dateTime.minusDays(1),DateUtils.format_ymds));
            if(CollectionUtil.isBlank(dailyCurrencyInfor)){
                continue;
            }
            DailyComprehensiveAnalysisInfo beforeDailyInfo = DailyInfoUtils.getNearDailyInfo(
                    dailyCurrencyInfor,dateTime.getHour(),dateTime.getMinute()
            );
            if(beforeDailyInfo!=null){
                BigDecimal price = new BigDecimal(beforeDailyInfo.getPriceCny());
                //BigDecimal marketCapUsd = new BigDecimal(beforeDailyInfo.getMarketCapCny());
                avgPriceUsdBefore = avgPriceUsdBefore.add(
                        price.multiply(weightInfo.getFixedWeights())
                            .multiply(new BigDecimal(1.162))
                );
            }

            DailyComprehensiveAnalysisInfo nowInfo = nowDailyInfoMap.get(weightInfo.getCmcId());
            if(nowInfo!=null){
                BigDecimal price = new BigDecimal(nowInfo.getPriceCny());
                //BigDecimal marketCapUsd = new BigDecimal(nowInfo.getMarketCapCny());
                avgPriceUsdNow = avgPriceUsdNow.add(
                        price.multiply(weightInfo.getFixedWeights())
                                .multiply(new BigDecimal(1.162))
                );
            }
        }
        if(avgPriceUsdNow.doubleValue()!=0){

            BigDecimal performance =  avgPriceUsdNow.subtract(avgPriceUsdBefore)
                    .divide(avgPriceUsdNow,4,BigDecimal.ROUND_DOWN);
            Integer score = null;
            String comment = null;
            if(performance.doubleValue()<-0.06){
                score = 1;
                comment = "主力出逃明显";
            }else if(-0.06<=performance.doubleValue()&&performance.doubleValue()<-0.045){
                score = 2;
                comment = "主力出逃明显";
            }else if(-0.045<=performance.doubleValue()&&performance.doubleValue()<-0.03){
                score = 3;
                comment = "主力开始出逃";
            }else if(-0.03<=performance.doubleValue()&&performance.doubleValue()<-0.015){
                score = 4;
                comment = "主力开始出逃";
            }else if(-0.015<=performance.doubleValue()&&performance.doubleValue()<=0){
                score = 5;
                comment = "主力参与度一般";
            }else if(0<=performance.doubleValue()&&performance.doubleValue()<0.015){
                score = 6;
                comment = "主力参与度一般";
            }else if(0.015<=performance.doubleValue()&&performance.doubleValue()<0.03){
                score = 7;
                comment = "主力开始进场";
            }else if(0.03<=performance.doubleValue()&&performance.doubleValue()<0.045){
                score = 8;
                comment = "主力开始进场";
            }else if(0.045<=performance.doubleValue()&&performance.doubleValue()<0.06){
                score = 9;
                comment = "主力进场明显";
            }else if(0.06<=performance.doubleValue()){
                score = 10;
                comment = "主力进场明显";
            }

            WeightsPerformance weightsPerformance = new WeightsPerformance();
            weightsPerformance.setPerformance(performance);
            weightsPerformance.setScore(score);
            weightsPerformance.setComment(comment);
            weightsPerformance.setCreateTime(createTime);
            this.insertPerformance(HbaseTableUtils.DAILY_WEIGHT_PERFORMANCE_INFO_TABLE_NAME
                    ,DateUtils.localDateTimeFormatString(dateTime,DateUtils.format_ymds)
                    ,HbaseTableUtils.DAILY_WEIGHT_PERFORMANCE_INFO_TABLE_FAMILY
                    ,HbaseTableUtils.DAILY_WEIGHT_PERFORMANCE_INFO_TABLE_QUALIFIER
                    ,weightsPerformance);
            return weightsPerformance;
        }
        return null;

    }


    /**
     * 获取权重货币
     * @return
     */
    private Map<String,CurrencyInfo> getWeightsCurrencyListMap() {
        Map<String,CurrencyInfo> currencyInfoMap = new HashMap<>();
        List<CurrencyInfo> currencyInfos = redisCacheComponent.getWeightsCurrencyList();
        if(CollectionUtil.isBlank(currencyInfos)){
            return null;
        }
        for (CurrencyInfo currencyInfo:currencyInfos) {
            currencyInfoMap.put(currencyInfo.getCmcId(),currencyInfo);
        }
        return currencyInfoMap;
    }


    /**
     * 获取货币信息
     * @return
     */
    private Map<String,CurrencyInfo> getCurrencyListMap() {
        Map<String,CurrencyInfo> currencyInfoMap = new HashMap<>();
        List<CurrencyInfo> currencyInfos = redisCacheComponent.getCurrencyList();
        if(CollectionUtil.isBlank(currencyInfos)){
            return null;
        }
        for (CurrencyInfo currencyInfo:currencyInfos) {
            currencyInfoMap.put(currencyInfo.getCmcId(),currencyInfo);
        }
        return currencyInfoMap;
    }


    /**
     * 计算量能变化
     * @param dailyInfoMap
     * @return
     */
    public QuantumEnergy calculateQuantumEnergy(Map<String, DailyComprehensiveAnalysisInfo> dailyInfoMap) {

        /*BigDecimal sumPriceMarketCapNow = new BigDecimal(0);
        BigDecimal sumMarketCapNow = new BigDecimal(0);
        BigDecimal sumTurnover24hBefore = new BigDecimal(0);
        BigDecimal sumTurnover24hNow = new BigDecimal(0);
        BigDecimal avgPriceNow = new BigDecimal(0);
        BigDecimal sumPriceBefore = new BigDecimal(0);
        BigDecimal volume = new BigDecimal(0);*/
        BigDecimal avgPriceNow = new BigDecimal(0);
        BigDecimal avgPriceB = new BigDecimal(0);
        BigDecimal sumVolumeNow = new BigDecimal(0);
        BigDecimal sumVolumeB = new BigDecimal(0);
        CurrencyInfo searchInfo = new CurrencyInfo();
        searchInfo.setWeights(true);
        List<CurrencyInfo> weightInfos = redisCacheComponent.getWeightsCurrencyList();
        QuantumEnergy quantumEnergy = new QuantumEnergy();

        for (CurrencyInfo weightInfo:weightInfos) {

            DailyComprehensiveAnalysisInfo nowInfo = dailyInfoMap.get(weightInfo.getCmcId());
            if(nowInfo == null) {
                continue;
            }
            LocalDateTime dateTime = DateUtils.dateToLocalDateTime(nowInfo.getCreateTime());
            if(quantumEnergy.getCreateTime()==null){
                quantumEnergy.setCreateTime(nowInfo.getCreateTime());
            }
            DailyComprehensiveAnalysisInfo beforeInfo;
            Map<String, List<DailyComprehensiveAnalysisInfo>> beforeMap
                    = coinMarketCapDataComponent.getDailyCurrencyInfor(nowInfo.getId()+"@"+DateUtils.getNextDayDateYMD(-1));
            if(CollectionUtil.isBlank(beforeMap)){
                continue;
            }
            beforeInfo = DailyInfoUtils.getNearDailyInfo(beforeMap
                    ,dateTime.getHour(),dateTime.getMinute());

            if(beforeInfo==null){
                continue;
            }



            if(MathUtils.isNumeric(nowInfo.getVolume24hCny())
                    &&MathUtils.isNumeric(nowInfo.getPriceCny())
                    &&MathUtils.isNumeric(nowInfo.getMarketCapCny())
                    &&MathUtils.isNumeric(beforeInfo.getVolume24hCny())
                    &&MathUtils.isNumeric(beforeInfo.getPriceCny())){

                BigDecimal nowPrice = new BigDecimal(nowInfo.getPriceCny());
                avgPriceNow = avgPriceNow.add(
                        nowPrice.multiply(weightInfo.getFixedWeights())
                        .multiply(new BigDecimal(1.162))
                );
                BigDecimal beforePrice = new BigDecimal(beforeInfo.getPriceCny());
                avgPriceB = avgPriceB.add(
                        beforePrice.multiply(weightInfo.getFixedWeights())
                        .multiply(new BigDecimal(1.162))
                );
                sumVolumeNow = sumVolumeNow.add(
                        new BigDecimal(nowInfo.getVolume24hCny())
                );
                sumVolumeB = sumVolumeB.add(
                        new BigDecimal(beforeInfo.getVolume24hCny())
                );
            }
        }


        quantumEnergy.setVolume(sumVolumeNow);
        quantumEnergy.setAvgPrice(avgPriceNow);
        quantumEnergy.setAvgTurnover24h(sumVolumeNow.divide(
                new BigDecimal(weightInfos.size()),4,BigDecimal.ROUND_DOWN));
        if(sumVolumeB.doubleValue()!=0){
            quantumEnergy.setTurnoverChangeRate(
                    sumVolumeNow.subtract(sumVolumeB)
                            .divide(sumVolumeB,4,BigDecimal.ROUND_DOWN)
            );
        }
        Integer score = null;
        String comment = null;
        if( avgPriceNow.doubleValue()-avgPriceB.doubleValue()<=-0.01
                &&quantumEnergy.getTurnoverChangeRate().doubleValue()>=1.5){
            score = 1;
            comment = "过去24h权重货币整体放量下跌";
        }else if(avgPriceNow.doubleValue()-avgPriceB.doubleValue()<=-0.01
                &&quantumEnergy.getTurnoverChangeRate().doubleValue()>=0.3
                &&quantumEnergy.getTurnoverChangeRate().doubleValue()<1.5 ){
            score = 2;
            comment = "过去24h权重货币整体量升价跌";
        }else if(avgPriceNow.doubleValue()-avgPriceB.doubleValue()<=-0.01
                &&quantumEnergy.getTurnoverChangeRate().doubleValue()>=-0.3
                &&quantumEnergy.getTurnoverChangeRate().doubleValue()<0.3 ){
            score = 3;
            comment = "过去24h权重货币整体恒量下跌";
        }else if(avgPriceNow.doubleValue()-avgPriceB.doubleValue()<=-0.01
                &&quantumEnergy.getTurnoverChangeRate().doubleValue()<-0.3 ){
            score = 4;
            comment = "过去24h权重货币整体缩量下跌";
        }else if(quantumEnergy.getTurnoverChangeRate().doubleValue()>-0.01
                &&quantumEnergy.getTurnoverChangeRate().doubleValue()<0 ){
            score = 5;
            comment = "过去24h权重货币整体量价均衡";
        }else if(quantumEnergy.getTurnoverChangeRate().doubleValue()>=0
                &&quantumEnergy.getTurnoverChangeRate().doubleValue()<0.01 ){
            score = 6;
            comment = "过去24h权重货币整体量价均衡";
        }else if(avgPriceNow.doubleValue()-avgPriceB.doubleValue()>=0.01
                &&quantumEnergy.getTurnoverChangeRate().doubleValue()<-0.3 ){
            score = 7;
            comment = "过去24h权重货币整体缩量上涨";
        }else if(avgPriceNow.doubleValue()-avgPriceB.doubleValue()>=0.01
                &&quantumEnergy.getTurnoverChangeRate().doubleValue()>=-0.3
                &&quantumEnergy.getTurnoverChangeRate().doubleValue()<0.3 ){
            score = 8;
            comment = "过去24h权重货币整体恒量上涨";
        }else if(avgPriceNow.doubleValue()-avgPriceB.doubleValue()>=0.01
                &&quantumEnergy.getTurnoverChangeRate().doubleValue()>=0.3
                &&quantumEnergy.getTurnoverChangeRate().doubleValue()<1.5 ){
            score = 9;
            comment = "过去24h权重货币整体量价齐升";
        }else if(avgPriceNow.doubleValue()-avgPriceB.doubleValue()>=0.01
                &&quantumEnergy.getTurnoverChangeRate().doubleValue()>=1.5){
            score = 10;
            comment = "过去24h权重货币整体放量上涨";
        }

        quantumEnergy.setScore(score);
        quantumEnergy.setComment(comment);

        this.insertPerformance(HbaseTableUtils.DAILY_QUANTUM_ENERGY_INFO_TABLE_NAME
                ,DateUtils.getCurrentDateString()
                ,HbaseTableUtils.DAILY_QUANTUM_ENERGY_INFO_TABLE_FAMILY
                ,HbaseTableUtils.DAILY_QUANTUM_ENERGY_INFO_QUALIFIER
                ,quantumEnergy);

        return quantumEnergy;

    }

    /**
     * 保存大盘强度综合分析
     * @param currentcyHighOrLow
     * @param moneyEffect
     * @param moneyEffect
     * @param weightsPerformance
     * @param quantumEnergy
     */
    public void insertDailyCurrencyInfor(CurrentcyHighOrLow currentcyHighOrLow, MoneyEffect moneyEffect
            , WeightsPerformance weightsPerformance
            , QuantumEnergy quantumEnergy) {
        DailyCurrencyInfor dailyCurrencyInfor = new DailyCurrencyInfor();
        dailyCurrencyInfor.setScore(new BigDecimal(0));
        if(currentcyHighOrLow!=null){
            dailyCurrencyInfor.setCurrentcyHighOrLow(currentcyHighOrLow);
            String score = currentcyHighOrLow.getScore();
            if(MathUtils.isNumeric(score)){
                dailyCurrencyInfor.setScore(dailyCurrencyInfor.getScore()
                        .add(new BigDecimal(score).multiply(new BigDecimal(0.3))));
            }
        }
        if(moneyEffect!=null){
            dailyCurrencyInfor.setMoneyEffect(moneyEffect);
            Integer score = moneyEffect.getScore();
            if(score!=null){
                dailyCurrencyInfor.setScore(dailyCurrencyInfor.getScore()
                        .add(new BigDecimal(score).multiply(new BigDecimal(0.15))));
            }
        }
        if(weightsPerformance!=null){
            dailyCurrencyInfor.setWeightsPerformance(weightsPerformance);
            Integer score = weightsPerformance.getScore();
            if(score!=null){
                dailyCurrencyInfor.setScore(dailyCurrencyInfor.getScore()
                        .add(new BigDecimal(score).multiply(new BigDecimal(0.3))));
            }
        }
        if(quantumEnergy!=null){
            dailyCurrencyInfor.setQuantumEnergy(quantumEnergy);
            Integer score = quantumEnergy.getScore();
            if(score!=null){
                dailyCurrencyInfor.setScore(dailyCurrencyInfor.getScore()
                        .add(new BigDecimal(score).multiply(new BigDecimal(0.25))));
            }
        }
        if(dailyCurrencyInfor.getScore().doubleValue()<4){
            dailyCurrencyInfor.setComment("大盘处于走弱态势");
        }else if(dailyCurrencyInfor.getScore().doubleValue()>=4
                && dailyCurrencyInfor.getScore().doubleValue()<6){
            dailyCurrencyInfor.setComment("大盘处于盘整态势");
        }else if(dailyCurrencyInfor.getScore().doubleValue()>=6){
            dailyCurrencyInfor.setComment("大盘处于走强态势");
        }

        redisServer.set(RedisKeysUtils.INDEX_EVERY_DAY_RECORDING,JSON.toJSONString(dailyCurrencyInfor));
        this.insertPerformance(HbaseTableUtils.DAILY_COMPREHENSIVE_ANALYSIS_INFO_TABLE_NAME
                ,DateUtils.getCurrentDateString()
                ,HbaseTableUtils.DAILY_COMPREHENSIVE_ANALYSIS_INFO_TABLE_FAMILY
                ,HbaseTableUtils.DAILY_COMPREHENSIVE_ANALYSIS_INFO_QUALIFIER
                ,dailyCurrencyInfor);

        try {
            HttpUtils.getAkka(akkaMakeGrailIndexToCacheUrl);
        } catch (Exception e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(), e);
        }
    }


    /**
     * 计算量能变化
     * @param cmcCurrencyInfos
     * @return
     */
    public List<DiagnosisQuantumEnergy> calculateDiagnosisQuantumEnergy(List<CmcCurrencyInfo> cmcCurrencyInfos) {
        List<DiagnosisQuantumEnergy> diagnosisQuantumEnergies = new ArrayList<>();

        List<CurrencyInfo> currencyInfos = redisCacheComponent.getDiagnosisCurrencyList();
        Map<String, CmcCurrencyInfo> infoMap = this.cmcCurrencyInfoListToMap(cmcCurrencyInfos);
        for (CurrencyInfo currencyInfo:currencyInfos) {
            CmcCurrencyInfo cmcInfo = infoMap.get(currencyInfo.getCmcId());
            if(cmcInfo==null){
                continue;
            }
            try {
                LocalDateTime dateTime = DateUtils.dateToLocalDateTime(cmcInfo.getCreateTime());
                Map<String, List<DailyComprehensiveAnalysisInfo>> yesterdayDailyMap =
                        coinMarketCapDataComponent.getDailyCurrencyInfor(
                                cmcInfo.getId() + "@" + DateUtils.getNextDayDateYMD(-1));
                if(CollectionUtil.isBlank(yesterdayDailyMap)){
                    throw new ErrorDataException("昨日货币信息数据查询失败！");
                }
                DailyComprehensiveAnalysisInfo yesterdayInfo =
                        DailyInfoUtils.getNearDailyInfo(yesterdayDailyMap
                                ,dateTime.getHour(),dateTime.getMinute());

                if(yesterdayInfo==null){
                    throw new ErrorDataException("昨日货币信息数据查询失败！");
                }

                if(MathUtils.isNotNumeric(cmcInfo.getPriceCny())
                        ||MathUtils.isNotNumeric(yesterdayInfo.getPriceCny())
                        ||MathUtils.isNotNumeric(cmcInfo.getVolume24hCny())
                        ||MathUtils.isNotNumeric(yesterdayInfo.getVolume24hCny())
                        ){
                    throw new ErrorDataException("计算量能变化获取数据有误！cmcid = "+cmcInfo.getId()+" "
                            +cmcInfo.getPriceCny()+ " "+ yesterdayInfo.getPriceCny()+" "
                            + cmcInfo.getVolume24hCny()+" "+yesterdayInfo.getVolume24hCny());
                }
                DiagnosisQuantumEnergy quantumEnergy = new DiagnosisQuantumEnergy();
                quantumEnergy.setCreateTime(cmcInfo.getCreateTime());
                quantumEnergy.setId(cmcInfo.getId());
                quantumEnergy.setMinute(DateUtils.dateToLocalDateTime(cmcInfo.getCreateTime()).getMinute());

                BigDecimal nowPrice = new BigDecimal(cmcInfo.getPriceCny());
                BigDecimal yesterdayPrice = new BigDecimal(yesterdayInfo.getPriceCny());
                BigDecimal nowVolume24h = new BigDecimal(cmcInfo.getVolume24hCny());
                BigDecimal yesterVolume24h = new BigDecimal(yesterdayInfo.getVolume24hCny());

                if(
                        yesterdayPrice.doubleValue()==0
                                ||yesterVolume24h.doubleValue()==0){
                    throw new ErrorDataException("计算量能变化获取数据有误！cmcid = "+cmcInfo.getId()+" "
                            +cmcInfo.getPriceCny()+ " "+ yesterdayInfo.getPriceCny()+" "
                            + cmcInfo.getVolume24hCny()+" "+yesterdayInfo.getVolume24hCny());
                }

                quantumEnergy.setVolume24h(nowVolume24h);
                BigDecimal priceChangeRate = nowPrice.subtract(yesterdayPrice)
                        .divide(yesterdayPrice, 4, BigDecimal.ROUND_DOWN);
                quantumEnergy.setPriceChangeRate(priceChangeRate);

                BigDecimal turnoverChangeRate = nowVolume24h.subtract(yesterVolume24h)
                        .divide(yesterVolume24h, 4, BigDecimal.ROUND_DOWN);
                quantumEnergy.setTurnoverChangeRate(turnoverChangeRate);

                Integer score = null;
                String comment = null;
                if(priceChangeRate.doubleValue()<=-0.02 && turnoverChangeRate.doubleValue()>=1.5){
                    score = 1;
                    comment = "放量下跌";
                }else if(priceChangeRate.doubleValue()<=-0.02
                        && turnoverChangeRate.doubleValue()>=0.3 && turnoverChangeRate.doubleValue()<1.5){
                    score = 2;
                    comment = "量升价跌";
                }else if(priceChangeRate.doubleValue()<=-0.02
                        && turnoverChangeRate.doubleValue()>=-0.3 && turnoverChangeRate.doubleValue()<0.3){
                    score = 3;
                    comment = "恒量下跌";
                }else if(priceChangeRate.doubleValue()<=-0.02
                        && turnoverChangeRate.doubleValue()<-0.3){
                    score = 4;
                    comment = "缩量下跌";
                }else if(priceChangeRate.doubleValue()>=-0.02 && priceChangeRate.doubleValue()<0 ){
                    score = 5;
                    comment = "量价均衡";
                }else if(priceChangeRate.doubleValue()>=0 && priceChangeRate.doubleValue()<0.02){
                    score = 6;
                    comment = "量价均衡";
                }else if(priceChangeRate.doubleValue()>=0.02
                        && turnoverChangeRate.doubleValue()<-0.3){
                    score = 7;
                    comment = "缩量上涨";
                }else if(priceChangeRate.doubleValue()>=0.02
                        && turnoverChangeRate.doubleValue()>=-0.3 && turnoverChangeRate.doubleValue()<0.3){
                    score = 8;
                    comment = "恒量上涨";
                }else if(priceChangeRate.doubleValue()>=0.02
                        && turnoverChangeRate.doubleValue()>=0.3 && turnoverChangeRate.doubleValue()<1.5){
                    score = 9;
                    comment = "量价齐升";
                }else if(priceChangeRate.doubleValue()>=0.02
                        && turnoverChangeRate.doubleValue()>=1.5 ){
                    score = 10;
                    comment = "放量上涨";
                }

                quantumEnergy.setScore(score);
                quantumEnergy.setComment(comment);
                diagnosisQuantumEnergies.add(quantumEnergy);
            } catch (Exception e) {
                e.printStackTrace();
                LogTrace.error(e.getMessage(),e);
                LogTrace.info("测试","cx","cx");
            }

        }
        return diagnosisQuantumEnergies;

    }


    /**
     * 旧计算量能方法
     * @param currencies
     * @return
     */
    public Map<String, DiagnosisQuantumEnergy> calculateDiagnosisQuantumEnergyBak(Map<String, List<CurrencyHistorical>> currencies) {
        if(currencies==null){
            currencies = this.getTodayCurrenciesFromHbase();
        }
        Map<String,DiagnosisQuantumEnergy> quantumEnergyMap = new HashMap<>();
        for (String key:currencies.keySet()) {
            List<CurrencyHistorical> currencyHistoricals = currencies.get(key);
            if(currencyHistoricals==null || currencyHistoricals.size()<2){
                continue;
            }
            BigDecimal afterClosingPrice = currencyHistoricals.get(0).getClosingPriceCny();
            BigDecimal afterTradingVolume = currencyHistoricals.get(0).getTradingVolume();
            BigDecimal beforeClosingPrice = currencyHistoricals.get(1).getClosingPriceCny();
            BigDecimal beforeTradingVolume = currencyHistoricals.get(1).getTradingVolume();
            if( afterClosingPrice==null
                    ||afterTradingVolume==null
                    ||beforeClosingPrice==null
                    ||beforeTradingVolume==null
                    ||beforeClosingPrice.doubleValue()==0
                    ||beforeTradingVolume.doubleValue()==0){
                continue;
            }
            DiagnosisQuantumEnergy quantumEnergy = new DiagnosisQuantumEnergy();
            BigDecimal priceChangeRate = afterClosingPrice.subtract(beforeClosingPrice)
                    .divide(beforeClosingPrice, 4, BigDecimal.ROUND_DOWN);
            quantumEnergy.setPriceChangeRate(priceChangeRate);
            BigDecimal turnoverChangeRate = afterTradingVolume.subtract(beforeTradingVolume)
                    .divide(beforeTradingVolume, 4, BigDecimal.ROUND_DOWN);
            quantumEnergy.setTurnoverChangeRate(turnoverChangeRate);

            Integer score = null;
            String comment = null;
            if(priceChangeRate.doubleValue()<0 && turnoverChangeRate.doubleValue()<-0.05){
                score = 1;
                comment = "卖出力量大于买入力量";
            }else if(priceChangeRate.doubleValue()<0
                    && turnoverChangeRate.doubleValue()>=-0.05 && turnoverChangeRate.doubleValue()<-0.02){
                score = 2;
                comment = "卖出力量大于买入力量";
            }else if(priceChangeRate.doubleValue()<0
                    && turnoverChangeRate.doubleValue()>=-0.02 && turnoverChangeRate.doubleValue()<0){
                score = 3;
                comment = "卖出力量大于买入力量";
            }else if(priceChangeRate.doubleValue()>0
                    && turnoverChangeRate.doubleValue()<0){
                score = 4;
                comment = "买入力量与卖出力量不明显";
            }else if(priceChangeRate.doubleValue()<0
                    && turnoverChangeRate.doubleValue()>=0 ){
                score = 5;
                comment = "买入力量与卖出力量不明显";
            }else if(priceChangeRate.doubleValue()>0
                    && turnoverChangeRate.doubleValue()>=0 && turnoverChangeRate.doubleValue()<0.01){
                score = 6;
                comment = "买入力量大于卖出力量";
            }else if(priceChangeRate.doubleValue()>0
                    && turnoverChangeRate.doubleValue()>=0.01 && turnoverChangeRate.doubleValue()<0.015){
                score = 7;
                comment = "买入力量大于卖出力量";
            }else if(priceChangeRate.doubleValue()>0
                    && turnoverChangeRate.doubleValue()>=0.015 && turnoverChangeRate.doubleValue()<0.03){
                score = 8;
                comment = "买入力量大于卖出力量";
            }else if(priceChangeRate.doubleValue()>0
                    && turnoverChangeRate.doubleValue()>=0.03 && turnoverChangeRate.doubleValue()<0.05){
                score = 9;
                comment = "买入力量大于卖出力量";
            }else if(priceChangeRate.doubleValue()>0
                    && turnoverChangeRate.doubleValue()>=0.05 ){
                score = 10;
                comment = "主力参与度高";
            }

            quantumEnergy.setScore(score);
            quantumEnergy.setComment(comment);
            quantumEnergy.setCreateTime(currencyHistoricals.get(0).getCreateTime());
            quantumEnergyMap.put(key,quantumEnergy);
        }
        currencyInfoHbaseComponent.insertHbaseString(HbaseTableUtils.CURRENCY_DIAGNOSIS_QUANTUM_ENERGY_INFO_TABLE_NAME
                ,DateUtils.getCurrentDateString()
                ,HbaseTableUtils.CURRENCY_DIAGNOSIS_QUANTUM_ENERGY_INFO_TABLE_FAMILY
                ,HbaseTableUtils.CURRENCY_DIAGNOSIS_QUANTUM_ENERGY_INFO_QUALIFIE
                ,JSON.toJSONString(quantumEnergyMap));
        return quantumEnergyMap;
    }


    /**
     * 获取货币历史
     * @return
     */
    private Map<String,List<CurrencyHistorical>> getTodayCurrenciesFromHbase() {
        Map<String,List<CurrencyHistorical>> currencies = null;
        try {
            String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.CURRENCY_HISTORICAL_DATA_INFO_TABLE_NAME
                    , HbaseTableUtils.CURRENCY_HISTORICAL_DATA_INFO_TABLE_FAMILY
                    , HbaseTableUtils.CURRENCY_HISTORICAL_DATA_INFO_TABLE_QUALIFIER
                    , DateUtils.getCurrentDateString());
            if(StringUtils.isBlank(data)){
                data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.CURRENCY_HISTORICAL_DATA_INFO_TABLE_NAME
                        , HbaseTableUtils.CURRENCY_HISTORICAL_DATA_INFO_TABLE_FAMILY
                        , HbaseTableUtils.CURRENCY_HISTORICAL_DATA_INFO_TABLE_QUALIFIER
                        , DateUtils.getNextDayDateYMD(-1));
            }
            if(StringUtils.isNotBlank(data)){
                JSONObject jsonObject = JSON.parseObject(data);
                currencies = new HashMap<>();
                for (String key:jsonObject.keySet()) {
                    JSONArray jsonArray = jsonObject.getJSONArray(key);
                    if(jsonArray!=null){
                        currencies.put(key,jsonArray.toJavaList(CurrencyHistorical.class));
                    }
                }
            }
        } catch (Exception e) {
            LogTrace.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return currencies;
    }


    /**
     * 计算流动性
     * @param dailyInfoMap
     * @param cmcCurrencyGlobalInfo
     * @return
     */
    public List<Liquidity> liquidity(Map<String, DailyComprehensiveAnalysisInfo> dailyInfoMap, CmcCurrencyGlobalInfo cmcCurrencyGlobalInfo) {

        LogTrace.info("计算货币流动性" , "dailyInfoMap" , "size="+dailyInfoMap.size());
        List<CurrencyInfo> currencyInfos = redisCacheComponent.getDiagnosisCurrencyList();
        List<Liquidity> liquidityList = new ArrayList<>();
        for (CurrencyInfo currencyInfo:currencyInfos) {
            DailyComprehensiveAnalysisInfo dailyInfo = dailyInfoMap.get(currencyInfo.getCmcId());

            if( dailyInfo == null
                    ||  MathUtils.isNotNumeric(dailyInfo.getVolume24hCny())
                    ||  MathUtils.isNotNumeric(dailyInfo.getMarketCapCny())
                    ||  MathUtils.isNotNumeric(cmcCurrencyGlobalInfo.getTotal24hVolumeCny())
                    ||  MathUtils.isNotNumeric(cmcCurrencyGlobalInfo.getTotalMarketCapCny())
                    ){
                continue;
            }
            LogTrace.info("计算货币流动性" , "dailyInfo",dailyInfo.toString() );

            Liquidity liquidity = new Liquidity();
            liquidity.setId(dailyInfo.getId());
            liquidity.setCreateTime(dailyInfo.getCreateTime());
            BigDecimal coinTurnover24h = new BigDecimal(dailyInfo.getVolume24hCny());
            BigDecimal coinMarketCap = new BigDecimal(dailyInfo.getMarketCapCny());
            BigDecimal total24hVolume = new BigDecimal(cmcCurrencyGlobalInfo.getTotal24hVolumeCny());
            BigDecimal totalMarketCap = new BigDecimal(cmcCurrencyGlobalInfo.getTotalMarketCapCny());
            if(coinMarketCap.doubleValue()!=0 && totalMarketCap.doubleValue()!=0){
                BigDecimal coinExchangeRate =coinTurnover24h.divide(coinMarketCap,4,BigDecimal.ROUND_DOWN);
                BigDecimal totalExchangeRate =total24hVolume.divide(totalMarketCap,4,BigDecimal.ROUND_DOWN);
                BigDecimal exchangeRatio =coinExchangeRate.divide(totalExchangeRate,4,BigDecimal.ROUND_DOWN);
                liquidity.setCoinExchangeRate(coinExchangeRate);
                liquidity.setMinute(DateUtils.dateToLocalDateTime(cmcCurrencyGlobalInfo.getCreateTime()).getMinute());

                liquidity.setTotalExchangeRate(totalExchangeRate);
                liquidity.setExchangeRatio(exchangeRatio);
                Integer score = null;
                String comment = null;
                if(exchangeRatio.doubleValue()<0.1){
                    score = 1;
                    comment = "投资者交易频率低";
                }else if(exchangeRatio.doubleValue()>=0.1 && exchangeRatio.doubleValue()<0.3){
                    score = 2;
                    comment = "投资者交易频率低";
                }else if(exchangeRatio.doubleValue()>=0.3 && exchangeRatio.doubleValue()<0.5){
                    score = 3;
                    comment = "投资者交易频率较低";
                }else if(exchangeRatio.doubleValue()>=0.5 && exchangeRatio.doubleValue()<1){
                    score = 4;
                    comment = "投资者交易频率较低";
                }else if(exchangeRatio.doubleValue()>=1 && exchangeRatio.doubleValue()<1.5){
                    score = 5;
                    comment = "投资者交易频率一般";
                }else if(exchangeRatio.doubleValue()>=1.5 && exchangeRatio.doubleValue()<2){
                    score = 6;
                    comment = "投资者交易频率一般";
                }else if(exchangeRatio.doubleValue()>=2 && exchangeRatio.doubleValue()<3){
                    score = 7;
                    comment = "投资者交易频率较高";
                }else if(exchangeRatio.doubleValue()>=3 && exchangeRatio.doubleValue()<4){
                    score = 8;
                    comment = "投资者交易频率较高";
                }else if(exchangeRatio.doubleValue()>=4 && exchangeRatio.doubleValue()<5){
                    score = 9;
                    comment = "投资者交易频率高";
                }else if(exchangeRatio.doubleValue()>=5){
                    score = 10;
                    comment = "投资者交易频率高";
                }

                liquidity.setScore(score);
                liquidity.setComment(comment);
                liquidityList.add(liquidity);
            }
        }
        LogTrace.info("计算货币流动性" , "liquidityList" , "size="+liquidityList.size());
        return liquidityList;
    }


    /**
     * 计算人气意愿
     * @return
     */
    public Map<String, PopularityIndicator> calculatePopularityIndicatorNew() {

        List<CurrencyInfo> currencyList = redisCacheComponent.getDiagnosisCurrencyList();
        LocalDateTime dateTime = LocalDateTime.now();
        LogTrace.info("计算人气意愿","calculatePopularityIndicatorNew",currencyList.size()+"");
        Map<String,PopularityIndicator> popularityIndicatorMap = new HashMap<>();
        for (CurrencyInfo currencyInfo:currencyList) {

            String rowKey = currencyInfo.getCmcId()+"@"
                    + DateUtils.localDateTimeFormatString(dateTime,DateUtils.format_ymds);

            Map<String, List<DailyComprehensiveAnalysisInfo>> dailyCurrencyInfor = coinMarketCapDataComponent.getDailyCurrencyInfor(rowKey);
            LocalDateTime dateTime1 = dateTime;
            List<Map<String,BigDecimal>> mapList = new ArrayList<>();
            for (int i = 1; i <= 26; i++) {
                LocalDateTime minusHours = dateTime.minusHours(i);
                if (!StringUtils.equals(
                        DateUtils.localDateTimeFormatString(dateTime1,DateUtils.format_ymds),
                        DateUtils.localDateTimeFormatString(minusHours,DateUtils.format_ymds)
                )) {
                    dateTime1 = minusHours;
                    dailyCurrencyInfor =
                            coinMarketCapDataComponent.getDailyCurrencyInfor(currencyInfo.getCmcId()+"@"
                                    + DateUtils.localDateTimeFormatString(minusHours,DateUtils.format_ymds));
                }
                String key = String.valueOf(minusHours.getHour());
                if(dailyCurrencyInfor == null){
                    LogTrace.info("计算人气意愿" , "dailyCurrencyInforIsNull",rowKey);
                    continue;
                }
                List<DailyComprehensiveAnalysisInfo> infos = dailyCurrencyInfor.get(key);
                if(CollectionUtil.isBlank(infos)){
                    continue;
                }
                mapList.add(this.getHourPrice(infos));

            }
            /*if(dateTime.getHour()<5){
                Map<String, List<DailyComprehensiveAnalysisInfo>> yesterdayDailyCurrencyInfor =
                        coinMarketCapDataComponent.getDailyCurrencyInfor(currencyInfo.getCmcId()+"@"+ DateUtils.getCurrentDateString());

                for (int i = 1; i <= dateTime.getHour(); i++) {
                    String key = String.valueOf(dateTime.getHour() - i);
                    List<DailyComprehensiveAnalysisInfo> list = todayDailyCurrencyInfor.get(key);
                    if(CollectionUtil.isBlank(list)){
                        continue;
                    }
                    mapList.add(this.getHourPrice(list));
                }
                for (int i = 1; i <= 5-dateTime.getHour(); i++) {
                    String key = String.valueOf(24 - i);
                    List<DailyComprehensiveAnalysisInfo> infos = yesterdayDailyCurrencyInfor.get(key);
                    if(CollectionUtil.isBlank(infos)){
                        continue;
                    }

                    mapList.add(this.getHourPrice(infos));
                }
            }else{
                for (int i = 1; i <= 5; i++) {

                    String key = String.valueOf(dateTime.getHour() - i);
                    List<DailyComprehensiveAnalysisInfo> infos = todayDailyCurrencyInfor.get(key);
                    if(CollectionUtil.isBlank(infos)){
                        continue;
                    }

                    mapList.add(this.getHourPrice(infos));
                }

            }*/


            try{
                BigDecimal sumHM = new BigDecimal(0);
                BigDecimal sumML = new BigDecimal(0);
                for (Map<String,BigDecimal> map:mapList) {
                    BigDecimal highestPriceCny = map.get("highestPriceCny");
                    BigDecimal lowestPriceCny = map.get("lowestPriceCny");
                    BigDecimal openingPriceCny = map.get("openingPriceCny");
                    if( highestPriceCny==null ||lowestPriceCny==null ||openingPriceCny==null){
                        continue;
                    }
                    sumHM = sumHM.add(
                            highestPriceCny.subtract(openingPriceCny)
                    );
                    sumML = sumML.add(
                            openingPriceCny.subtract(lowestPriceCny)
                    );
                }
                PopularityIndicator popularityIndicator = new PopularityIndicator();
                popularityIndicator.setId(currencyInfo.getCmcId());
                popularityIndicator.setCreateTime(DateUtils.localDateTimeToDate(dateTime));
                if(sumML.doubleValue()!=0){
                    BigDecimal ar = sumHM.divide(sumML,4,BigDecimal.ROUND_DOWN);
                    popularityIndicator.setAr(ar.multiply(new BigDecimal(100)));
                }else{
                    popularityIndicator.setAr(new BigDecimal(0));
                }

                Integer score = null;
                String comment = null;
                if(popularityIndicator.getAr().doubleValue()>=0 && popularityIndicator.getAr().doubleValue()<15){
                    score = 1;
                    comment = "近期卖方意愿强";
                }else if(popularityIndicator.getAr().doubleValue()>=15 && popularityIndicator.getAr().doubleValue()<40){
                    score = 2;
                    comment = "近期卖方意愿强";
                }else if(popularityIndicator.getAr().doubleValue()>=40 && popularityIndicator.getAr().doubleValue()<60){
                    score = 3;
                    comment = "近期卖方意愿较强";
                }else if(popularityIndicator.getAr().doubleValue()>=60 && popularityIndicator.getAr().doubleValue()<80){
                    score = 4;
                    comment = "近期卖方意愿较强";
                }else if(popularityIndicator.getAr().doubleValue()>=80 && popularityIndicator.getAr().doubleValue()<100){
                    score = 5;
                    comment = "近期买卖意愿均衡";
                }else if(popularityIndicator.getAr().doubleValue()>=100 && popularityIndicator.getAr().doubleValue()<120){
                    score = 6;
                    comment = "近期买卖意愿均衡";
                }else if(popularityIndicator.getAr().doubleValue()>=120 && popularityIndicator.getAr().doubleValue()<145){
                    score = 7;
                    comment = "近期买方意愿较强";
                }else if(popularityIndicator.getAr().doubleValue()>=145 && popularityIndicator.getAr().doubleValue()<180){
                    score = 8;
                    comment = "近期买方意愿较强";
                }else if(popularityIndicator.getAr().doubleValue()>=180 && popularityIndicator.getAr().doubleValue()<200){
                    score = 9;
                    comment = "近期买方意愿强";
                }else if(popularityIndicator.getAr().doubleValue()>=200){
                    score = 10;
                    comment = "近期买方意愿强";
                }

                popularityIndicator.setScore(score);
                popularityIndicator.setComment(comment);

                popularityIndicatorMap.put(currencyInfo.getCmcId(),popularityIndicator);
            }catch (Exception e) {
                e.printStackTrace();
                LogTrace.error(e.getMessage(),e);
                LogTrace.info("测试","cx","cx");
            }


        }
        return popularityIndicatorMap;
    }

    /**
     * 获取每小时价格
     * @param infos
     * @return
     */
    private Map<String,BigDecimal> getHourPrice(List<DailyComprehensiveAnalysisInfo> infos) {
        Map<String,BigDecimal> map = new HashMap<>();
        BigDecimal highestPriceCny = null;
        BigDecimal lowestPriceCny = null;
        BigDecimal openingPriceCny = null;
        for (DailyComprehensiveAnalysisInfo info:infos) {
            if(MathUtils.isNotNumeric(info.getPriceCny())){
                continue;
            }
            BigDecimal price = new BigDecimal(info.getPriceCny());
            if(openingPriceCny==null ){
                openingPriceCny = price;
            }
            if(lowestPriceCny==null || price.doubleValue()<lowestPriceCny.doubleValue()){
                lowestPriceCny = price;
            }
            if(highestPriceCny==null || price.doubleValue()>highestPriceCny.doubleValue()){
                highestPriceCny = price;
            }
        }
        map.put("highestPriceCny",highestPriceCny);
        map.put("lowestPriceCny",lowestPriceCny);
        map.put("openingPriceCny",openingPriceCny);
        return map;
    }


    /**
     * 计算人气意愿指标
     * @param currencies
     * @return
     */
    public Map<String, PopularityIndicator> calculatePopularityIndicator(Map<String, List<CurrencyHistorical>> currencies) {
        if(currencies==null){
            currencies = this.getTodayCurrenciesFromHbase();
        }
        Map<String,PopularityIndicator> popularityIndicatorMap = new HashMap<>();

        List<CurrencyInfo> currencyList = redisCacheComponent.getDiagnosisCurrencyList();
        for (CurrencyInfo currencyInfo:currencyList) {
            List<CurrencyHistorical> currencyHistoricals = currencies.get(currencyInfo.getCmcId());
            if(CollectionUtils.isEmpty(currencyHistoricals)){
                continue;
            }
            try{
                BigDecimal sumHM = new BigDecimal(0);
                BigDecimal sumML = new BigDecimal(0);
                for (int i = 0; i < (currencyHistoricals.size()<5?currencyHistoricals.size():5); i++) {
                    CurrencyHistorical historical = currencyHistoricals.get(i);
                    BigDecimal highestPriceCny = historical.getHighestPriceCny();
                    BigDecimal lowestPriceCny = historical.getLowestPriceCny();
                    BigDecimal openingPriceCny = historical.getOpeningPriceCny();
                    if( highestPriceCny==null ||lowestPriceCny==null ||openingPriceCny==null){
                        continue;
                    }
                    sumHM = sumHM.add(
                            highestPriceCny.subtract(openingPriceCny)
                    );
                    sumML = sumML.add(
                            openingPriceCny.subtract(lowestPriceCny)
                    );
                }
                PopularityIndicator popularityIndicator = new PopularityIndicator();
                popularityIndicator.setId(currencyInfo.getCmcId());
                if(sumML.doubleValue()!=0){
                    BigDecimal ar = sumHM.divide(sumML,4,BigDecimal.ROUND_DOWN);
                    popularityIndicator.setAr(ar.multiply(new BigDecimal(100)));
                    popularityIndicator.setCreateTime(currencyHistoricals.get(0).getCreateTime());

                    Integer score = null;
                    String comment = null;
                    if(popularityIndicator.getAr().doubleValue()>=0 && popularityIndicator.getAr().doubleValue()<15){
                        score = 1;
                        comment = "卖方意愿强烈";
                    }else if(popularityIndicator.getAr().doubleValue()>=15 && popularityIndicator.getAr().doubleValue()<40){
                        score = 2;
                        comment = "卖方意愿强烈";
                    }else if(popularityIndicator.getAr().doubleValue()>=40 && popularityIndicator.getAr().doubleValue()<55){
                        score = 3;
                        comment = "卖方意愿较高";
                    }else if(popularityIndicator.getAr().doubleValue()>=55 && popularityIndicator.getAr().doubleValue()<80){
                        score = 4;
                        comment = "卖方意愿较高";
                    }else if(popularityIndicator.getAr().doubleValue()>=80 && popularityIndicator.getAr().doubleValue()<100){
                        score = 5;
                        comment = "买卖意愿均衡";
                    }else if(popularityIndicator.getAr().doubleValue()>=100 && popularityIndicator.getAr().doubleValue()<120){
                        score = 6;
                        comment = "买卖意愿均衡";
                    }else if(popularityIndicator.getAr().doubleValue()>=120 && popularityIndicator.getAr().doubleValue()<145){
                        score = 7;
                        comment = "买方意愿较高";
                    }else if(popularityIndicator.getAr().doubleValue()>=145 && popularityIndicator.getAr().doubleValue()<180){
                        score = 8;
                        comment = "买方意愿较高";
                    }else if(popularityIndicator.getAr().doubleValue()>=180 && popularityIndicator.getAr().doubleValue()<200){
                        score = 9;
                        comment = "买方意愿强烈";
                    }else if(popularityIndicator.getAr().doubleValue()>=200){
                        score = 10;
                        comment = "买方意愿强烈";
                    }

                    popularityIndicator.setScore(score);
                    popularityIndicator.setComment(comment);
                }

                popularityIndicatorMap.put(currencyInfo.getCmcId(),popularityIndicator);
            }catch (Exception e) {
                e.printStackTrace();
                LogTrace.error(e.getMessage(),e);
                LogTrace.info("测试","cx","cx");
            }

        }
        try {
            HttpUtils.getAkka(tirserviceApiMakePopularityARIndexDataUrl);
        } catch (Exception e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(),e);
        }
        currencyInfoHbaseComponent.insertHbaseString(HbaseTableUtils.POPULARITY_INDICATOR_INFO_TABLE_NAME
                ,DateUtils.getCurrentDateString()
                ,HbaseTableUtils.POPULARITY_INDICATOR_INFO_TABLE_FAMILY
                ,HbaseTableUtils.POPULARITY_INDICATOR_INFO_QUALIFIER
                ,JSON.toJSONString(popularityIndicatorMap));
        return popularityIndicatorMap;
    }


    /**
     * 保存市场表现
     * @param cmcCurrencyInfos
     * @param broaderIndex
     * @param industryIndices
     * @return
     */
    public List<DiagnosisMarketPerformance> calculateDiagnosisMarketPerformance(List<CmcCurrencyInfo> cmcCurrencyInfos
            , BroaderIndex broaderIndex, List<IndustryIndex> industryIndices) {
        try {
        	LogTrace.beginTrace("计算市场表现数据开始");
            if(cmcCurrencyInfos==null || cmcCurrencyInfos.size()<20){
                throw new ErrorDataException("获取cmc货币信息失败！");
            }
            Map<String, CmcCurrencyInfo> infoMap = this.cmcCurrencyInfoListToMap(cmcCurrencyInfos);
            if(broaderIndex==null || CollectionUtils.isEmpty(industryIndices)){
                throw new ErrorDataException("大盘、行业信息为空！");
            }

            Date date = new Date();
            LocalDateTime dateTime = DateUtils.dateToLocalDateTime(date);
            if(dateTime.getHour()<8){
                dateTime = dateTime.minusDays(1);
                date = DateUtils.localDateTimeToDate(dateTime);
            }
            String dateFormatString = DateUtils.dateFormatString(date, DateUtils.format_ymd);
            dateTime = LocalDateTime.parse(dateFormatString+" 08:00:00",DateUtils.format_ymdhms);
            date = DateUtils.localDateTimeToDate(dateTime);
            /*Date nearDate = currencyInfoHbaseService.selectAfterNearDate(
                    DateUtils.localDateTimeFormatString(dateTime,DateUtils.format_ymdhms));
            List<CmcCurrencyInfo> beforeInfos = coinMarketCapDataComponent.getCmcInfosByDate(nearDate);
            if( CollectionUtils.isEmpty(beforeInfos)){
                throw new ErrorDataException("获取八点数据失败！");
            }
            Map<String, CmcCurrencyInfo> beforeInfoMap = this.cmcCurrencyInfoListToMap(beforeInfos);*/
            BroaderIndex beforeBroaderIndex = null;


            String broaderIndicesData = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.HOME_INDEX_EVERY_DAY_RECORDING_TABLE_NAME
                    , HbaseTableUtils.HOME_INDEX_EVERY_DAY_RECORDING_TABLE_FAMILY
                    , HbaseTableUtils.EVERY_DAY_BROADER_INDEX_QUALIFIER
                    , DateUtils.dateFormatString(date,DateUtils.format_ymds)
            );

            /*if(StringUtils.isBlank(broaderIndicesData)){
                broaderIndicesData = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.HOME_INDEX_EVERY_DAY_RECORDING_TABLE_NAME
                        , HbaseTableUtils.HOME_INDEX_EVERY_DAY_RECORDING_TABLE_FAMILY
                        , HbaseTableUtils.EVERY_DAY_BROADER_INDEX_QUALIFIER
                        , DateUtils.getNextDayDateYMD(-1));

            }*/
            List<BroaderIndex> broaderIndices = null;
            if(StringUtils.isNotBlank(broaderIndicesData)){
                JSONArray jsonArray = JSONArray.parseArray(broaderIndicesData);
                broaderIndices = jsonArray.toJavaList(BroaderIndex.class);
            }
            if(CollectionUtil.isNotBlank(broaderIndices)){

                long min = Long.MAX_VALUE;
                for (BroaderIndex index:broaderIndices) {
                    if(index.getCreateTime()==null){
                        continue;
                    }
                    long abs = Math.abs(index.getCreateTime().getTime() - date.getTime());
                    if(abs <min){
                        min = abs;
                        beforeBroaderIndex = index;
                    }
                }
            }

            if(beforeBroaderIndex==null){
                throw new ErrorDataException("未查询到前一时刻的大盘指数！");
            }
            BigDecimal broaderChangeRate = broaderIndex.getBroaderIndex().subtract(beforeBroaderIndex.getBroaderIndex())
                    .divide(beforeBroaderIndex.getBroaderIndex(),4,BigDecimal.ROUND_DOWN);
            List<DiagnosisMarketPerformance> diagnosisMarketPerformances = new ArrayList<>();



            List<CurrencyInfo> currencyList = redisCacheComponent.getCurrencyList();

            for (CurrencyInfo currencyInfo:currencyList) {
                try{
                    CmcCurrencyInfo info = infoMap.get(currencyInfo.getCmcId());
                    if(info==null){
                        continue;
                    }
                    Map<String, List<DailyComprehensiveAnalysisInfo>> dailyMap = coinMarketCapDataComponent.getDailyCurrencyInfor(
                            currencyInfo.getCmcId() + "@" + DateUtils.dateFormatString(date, DateUtils.format_ymds) );
                    DailyComprehensiveAnalysisInfo beforeInfo = DailyInfoUtils.getNearDailyInfo(dailyMap,8,0);
                    if(beforeInfo==null){
                        continue;
                    }

                    if( MathUtils.isNotNumeric(info.getPriceCny())
                            ||MathUtils.isNotNumeric(beforeInfo.getPriceCny())){
                        continue;
                    }

                    DiagnosisMarketPerformance diagnosisMarketPerformance = new DiagnosisMarketPerformance();
                    diagnosisMarketPerformance.setBroaderChangeRate(broaderChangeRate);
                    diagnosisMarketPerformance.setId(info.getId());
                    diagnosisMarketPerformance.setCreateTime(info.getCreateTime());
                    diagnosisMarketPerformance.setMinute(DateUtils.dateToLocalDateTime(info.getCreateTime()).getMinute());
                    BigDecimal nowPriceCny = new BigDecimal(info.getPriceCny());
                    BigDecimal beforePriceCny = new BigDecimal(beforeInfo.getPriceCny());
                    BigDecimal priceChangeRate = nowPriceCny.subtract(beforePriceCny)
                            .divide(beforePriceCny, 4, BigDecimal.ROUND_DOWN);
                    diagnosisMarketPerformance.setPriceChangeRate(priceChangeRate);



                    CurrencyIndustryMiddle currencyIndustryMiddle = new CurrencyIndustryMiddle();
                    currencyIndustryMiddle.setCurrencyId(currencyInfo.getId());
                    currencyIndustryMiddle = currencyIndustryMiddleService.selectByEntity(currencyIndustryMiddle);
                    if(currencyIndustryMiddle==null){
                        LogTrace.info(LogTraceKeysUtils.CMC_DATA_CALCULATE_COMPONENT, LogTraceKeysUtils.DATA,"未查询到货币对应行业配置！");
                        continue;
                        //throw new ErrorDataException("未查询到"+info.getId()+"货币对应行业配置！");
                    }
                    CurrencyIndustryCategory currencyIndustry = new CurrencyIndustryCategory();
                    currencyIndustry.setId(currencyIndustryMiddle.getIndustryCategoryId());
                    currencyIndustry = currencyIndustryCategoryService.selectByEntity(currencyIndustry);
                    if(currencyIndustry==null){
                        LogTrace.info(LogTraceKeysUtils.CMC_DATA_CALCULATE_COMPONENT, LogTraceKeysUtils.DATA,"未查询到货币对应行业配置！");
                        throw new ErrorDataException("未查询到"+currencyIndustryMiddle.getIndustryCategoryId()+"对应行业！");
                    }

                    while (currencyIndustry.getParentId()!=null && currencyIndustry.getParentId().intValue()!=0){
                        Integer parentId = currencyIndustry.getParentId();
                        currencyIndustry = new CurrencyIndustryCategory();
                        currencyIndustry.setId(parentId);
                        currencyIndustry = currencyIndustryCategoryService.selectByEntity(currencyIndustry);
                        if(currencyIndustry==null){
                            LogTrace.info(LogTraceKeysUtils.CMC_DATA_CALCULATE_COMPONENT, LogTraceKeysUtils.DATA,"未查询到货币对应行业配置！");
                            break;
                            //throw new ErrorDataException("未查询到"+parentId+"对应行业！");
                        }
                    }
                    /*if(currencyIndustry.getParentId()!=null && currencyIndustry.getParentId().intValue()!=0){
                        Integer parentId = currencyIndustry.getParentId();
                        currencyIndustry = new CurrencyIndustryCategory();
                        currencyIndustry.setId(parentId);
                        currencyIndustry = currencyIndustryCategoryService.selectByEntity(currencyIndustry);
                        if(currencyIndustry==null){
                            LogTrace.info(LogTraceKeysUtils.CMC_DATA_CALCULATE_COMPONENT, LogTraceKeysUtils.DATA,"未查询到货币对应行业配置！");
                            continue;
                        }
                    }*/

                    String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.HOME_INDEX_EVERY_DAY_RECORDING_TABLE_NAME
                            , HbaseTableUtils.HOME_INDEX_EVERY_DAY_RECORDING_TABLE_FAMILY
                            , HbaseTableUtils.CALCULATE_TICKER_QUALIFIER
                            , currencyIndustry.getId()+"@"+DateUtils.dateFormatString(date,DateUtils.format_ymds));
                    JSONArray jsonArray = null;
                    if(StringUtils.isNotBlank(data)){
                        jsonArray = JSON.parseArray(data);
                    }
                    if(CollectionUtil.isBlank(jsonArray)){
                        throw new ErrorDataException("未查询到前一刻"+currencyIndustry.getId()+"对应行业指数数据！");
                    }
                    List<IndustryIndex> industryIndexList = jsonArray.toJavaList(IndustryIndex.class);
                    if(industryIndexList==null || industryIndexList.size()<2){
                        throw new ErrorDataException("未查询到前一刻"+currencyIndustry.getId()+"对应行业指数数据！");
                    }

                    IndustryIndex beforeIndustryIndex = null;
                    if(CollectionUtil.isNotBlank(industryIndexList)){
                        long min = Long.MAX_VALUE;
                        for (IndustryIndex index:industryIndexList) {
                            if(index.getCreateTime()==null){
                                continue;
                            }
                            long abs = Math.abs(index.getCreateTime().getTime() - date.getTime());
                            if(abs <min){
                                min = abs;
                                beforeIndustryIndex = index;
                            }
                        }
                    }
                    if(beforeIndustryIndex==null){
                        throw new ErrorDataException("未查询到前一刻"+currencyIndustry.getId()+"对应行业指数数据！");
                    }
                    IndustryIndex nowIndustryIndex = null;
                    for (IndustryIndex industryIndex:industryIndices) {
                        if(industryIndex.getCurrencyIndustryCategoryId().equals(beforeIndustryIndex.getCurrencyIndustryCategoryId())){
                            nowIndustryIndex = industryIndex;
                            break;
                        }
                    }

                    if(nowIndustryIndex==null){
                        throw new ErrorDataException("未查询到后一刻"+beforeIndustryIndex.getCurrencyIndustryCategoryId()+"对应行业指数数据！");
                    }
                    BigDecimal industryChangeRate = nowIndustryIndex.getIndustryIndex().subtract(beforeIndustryIndex.getIndustryIndex())
                            .divide(beforeIndustryIndex.getIndustryIndex(), 4, BigDecimal.ROUND_DOWN);

                    diagnosisMarketPerformance.setIndustryChangeRate(industryChangeRate);

                    if(     diagnosisMarketPerformance.getBroaderChangeRate()==null
                            ||diagnosisMarketPerformance.getIndustryChangeRate()==null
                            ||diagnosisMarketPerformance.getPriceChangeRate()==null){
                        throw new ErrorDataException("市场表现计算失败！diagnosisMarketPerformance:"+JSON.toJSONString(diagnosisMarketPerformance));
                    }

                    if(diagnosisMarketPerformance.getPriceChangeRate().doubleValue()>
                            diagnosisMarketPerformance.getBroaderChangeRate().doubleValue()
                            && diagnosisMarketPerformance.getPriceChangeRate().doubleValue()>
                            diagnosisMarketPerformance.getIndustryChangeRate().doubleValue()){
                        diagnosisMarketPerformance.setComment("该货币价格跑赢大盘以及行业平均");
                    }else if(diagnosisMarketPerformance.getPriceChangeRate().doubleValue()>
                            diagnosisMarketPerformance.getBroaderChangeRate().doubleValue()
                            || diagnosisMarketPerformance.getPriceChangeRate().doubleValue()>
                            diagnosisMarketPerformance.getIndustryChangeRate().doubleValue()){
                        diagnosisMarketPerformance.setComment("该货币价格跑赢大盘或者行业平均");
                    }else if(diagnosisMarketPerformance.getPriceChangeRate().doubleValue()<
                            diagnosisMarketPerformance.getBroaderChangeRate().doubleValue()
                            && diagnosisMarketPerformance.getPriceChangeRate().doubleValue()<
                            diagnosisMarketPerformance.getIndustryChangeRate().doubleValue()){
                        diagnosisMarketPerformance.setComment("该货币价格没有跑赢大盘和行业平均");
                    }
                    diagnosisMarketPerformances.add(diagnosisMarketPerformance);

                } catch (Throwable e) {
//                } catch (ErrorDataException|HbaseConnectionExcetion|IOException|HbaseGetTableExcetion|HbaseCloseExcetion e) {
                    e.printStackTrace();
//                    LogTrace.error(e.getMessage(), e);
                }


            }



            return diagnosisMarketPerformances;

        } catch (ErrorDataException|HbaseConnectionExcetion|IOException|HbaseGetTableExcetion|HbaseCloseExcetion e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(), e);
        }
        return null;
    }


    /**
     * 保存市场表现
     * @param diagnosisMarketPerformances
     */
    public void saveDiagnosisMarketPerformance(List<DiagnosisMarketPerformance> diagnosisMarketPerformances) {
        for (DiagnosisMarketPerformance diagnosisMarketPerformance:diagnosisMarketPerformances) {
            try {
                String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.CURRENCY_DIAGNOSIS_MARKET_PERFORMANCE_TABLE_NAME
                        , HbaseTableUtils.CURRENCY_DIAGNOSIS_MARKET_PERFORMANCE_TABLE_FAMILY
                        , HbaseTableUtils.CURRENCY_DIAGNOSIS_MARKET_PERFORMANCE_QUALIFIER
                        , diagnosisMarketPerformance.getId()+"@"+DateUtils.getCurrentDateString());
                JSONObject mainObject;
                if(StringUtils.isBlank(data)){
                    mainObject = new JSONObject();
                }else{
                    mainObject = JSON.parseObject(data);
                }
                String key = DateUtils.dateToLocalDateTime(diagnosisMarketPerformance.getCreateTime()).getHour()+"";
                JSONArray jsonArray = mainObject.getJSONArray(key);
                if(jsonArray==null){
                    jsonArray = new JSONArray();
                }
                jsonArray.add(diagnosisMarketPerformance);
                mainObject.put(key,jsonArray);
                currencyInfoHbaseComponent.insertHbaseString(HbaseTableUtils.CURRENCY_DIAGNOSIS_MARKET_PERFORMANCE_TABLE_NAME
                        ,diagnosisMarketPerformance.getId()+"@"+DateUtils.getCurrentDateString()
                        ,HbaseTableUtils.CURRENCY_DIAGNOSIS_MARKET_PERFORMANCE_TABLE_FAMILY
                        ,HbaseTableUtils.CURRENCY_DIAGNOSIS_MARKET_PERFORMANCE_QUALIFIER
                        ,mainObject.toJSONString());

//                try{
//                    HttpUtils.getAkka(akkaMakeIndustryToCacheOfUrl);
//                    HttpUtils.getAkka(getMarketPerURL);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    LogTrace.error(e.getMessage(), e);
//                }
            } catch (Exception e) {
                e.printStackTrace();
                LogTrace.error(e.getMessage(), e);
            }
        }


    }


    /**
     * 计算压力支撑
     * @param cmcInfoMap
     * @return
     */
    public List<DiagnosisPressureSupporte> calculateDiagnosisPressureSupporte(Map<String,CmcCurrencyInfo> cmcInfoMap) {
        List<DiagnosisPressureSupporte> diagnosisPressureSupportes = new ArrayList<>();
        List<CurrencyInfo> currencyList = redisCacheComponent.getCurrencyList();
        for (CurrencyInfo currencyInfo:currencyList) {
            CmcCurrencyInfo info = cmcInfoMap.get(currencyInfo.getCmcId());
            if(info==null){continue;}
            try {
                DiagnosisPressureSupporte diagnosisPressureSupporte = new DiagnosisPressureSupporte();
                diagnosisPressureSupporte.setId(info.getId());
                diagnosisPressureSupporte.setCreateTime(info.getCreateTime());
                diagnosisPressureSupporte.setMinute(DateUtils.dateToLocalDateTime(info.getCreateTime()).getMinute());
                if(MathUtils.isNumeric(info.getPriceCny())){
                    diagnosisPressureSupporte.setPriceCny(new BigDecimal(info.getPriceCny()));
                }

                Map<String, List<CurrencyHistorical>> currenciesMap = this.getTodayCurrenciesFromHbase();

                List<CurrencyHistorical> currencyHistoricals = currenciesMap.get(info.getId());
                if(CollectionUtils.isEmpty(currencyHistoricals)){
                    throw new ErrorDataException("查询数据库货币历史信息失败 cmcid："+info.getId());
                }

                CurrencyHistorical historical = currencyHistoricals.get(0);
                BigDecimal closingPrice = historical.getClosingPriceCny();
                BigDecimal lowestPrice = historical.getLowestPriceCny();
                if(closingPrice==null || lowestPrice==null){
                    throw new ErrorDataException("查询历史货币参数信息失败 cmcid："+info.getId()
                            +";historical:"+JSON.toJSONString(historical)+";");
                }
                BigDecimal emotionalPressure = closingPrice.subtract(
                        closingPrice.subtract(lowestPrice).multiply(new BigDecimal(0.382))
                );
                diagnosisPressureSupporte.setEmotionalPressure(emotionalPressure);
                BigDecimal marketSupport = closingPrice.subtract(
                        closingPrice.subtract(lowestPrice).multiply(new BigDecimal(0.618))
                );
                diagnosisPressureSupporte.setMarketSupport(marketSupport);
                BigDecimal price = diagnosisPressureSupporte.getPriceCny();
                if(price.doubleValue()>emotionalPressure.doubleValue()){
                    diagnosisPressureSupporte.setComment("价格在支撑位上，短期行情有支撑");
                }else if(
                        (price.doubleValue()>marketSupport.doubleValue()
                        &&price.doubleValue()<emotionalPressure.doubleValue())
                        || price.doubleValue()==marketSupport.doubleValue()
                        || price.doubleValue()==emotionalPressure.doubleValue()
                        ){
                    diagnosisPressureSupporte.setComment("价格跌破1支撑位，短期可能有下跌趋势");
                }else if(price.doubleValue()<marketSupport.doubleValue()){
                    diagnosisPressureSupporte.setComment("价格跌破2支撑位，短期行情失去支撑");
                }
                /*diagnosisPressureSupporte.setComment("1支撑位是"+String.format("%.2f", emotionalPressure.doubleValue())
                        +"元，2支撑位"+String.format("%.2f", marketSupport.doubleValue())+"元");*/
                diagnosisPressureSupportes.add(diagnosisPressureSupporte);
            } catch (Exception e) {
                e.printStackTrace();
                LogTrace.error(e.getMessage(), e);
            }

        }
        return diagnosisPressureSupportes;

    }

    /**
     * 保存压力支撑
     * @param diagnosisPressureSupportes
     */
    public void saveDiagnosisPressureSupporte(List<DiagnosisPressureSupporte> diagnosisPressureSupportes) {
        for (DiagnosisPressureSupporte pressureSupporte:diagnosisPressureSupportes) {
            try {
                Date createTime = pressureSupporte.getCreateTime();
                String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.CURRENCY_DIAGNOSIS_PRESSURE_SUPPORT_TABLE_NAME
                        , HbaseTableUtils.CURRENCY_DIAGNOSIS_PRESSURE_SUPPORT_TABLE_FAMILY
                        , HbaseTableUtils.CURRENCY_DIAGNOSIS_PRESSURE_SUPPORT_QUALIFIER
                        , pressureSupporte.getId()+"@"+DateUtils.dateFormatString(createTime,DateUtils.format_ymds));
                JSONObject mainObject;
                if(StringUtils.isBlank(data)){
                    mainObject = new JSONObject();
                }else{
                    mainObject = JSON.parseObject(data);
                }
                String key = DateUtils.dateToLocalDateTime(createTime).getHour()+"";
                JSONArray jsonArray = mainObject.getJSONArray(key);
                if(jsonArray==null){
                    jsonArray = new JSONArray();
                }
                jsonArray.add(pressureSupporte);
                mainObject.put(key,jsonArray);
                currencyInfoHbaseComponent.insertHbaseString(HbaseTableUtils.CURRENCY_DIAGNOSIS_PRESSURE_SUPPORT_TABLE_NAME
                        ,pressureSupporte.getId()+"@"+DateUtils.dateFormatString(createTime,DateUtils.format_ymds)
                        ,HbaseTableUtils.CURRENCY_DIAGNOSIS_PRESSURE_SUPPORT_TABLE_FAMILY
                        ,HbaseTableUtils.CURRENCY_DIAGNOSIS_PRESSURE_SUPPORT_QUALIFIER
                        ,mainObject.toJSONString());

                HttpUtils.getAkka(getPressureSupURL);
            } catch (Exception e) {
                e.printStackTrace();
                LogTrace.error(e.getMessage(), e);
            }
        }


    }


    /**
     * 计算货币诊断得分
     * @param googleTrends
     * @param diagnosisQuantumEnergies
     * @param liquidities
     * @param popularityIndicatorMap
     * @return
     */
    public List<DiagnosisScore> calculateDiagnosisScore(List<TrendsInfo> googleTrends
            , List<DiagnosisQuantumEnergy> diagnosisQuantumEnergies
            , List<Liquidity> liquidities, Map<String, PopularityIndicator> popularityIndicatorMap) {
        List<DiagnosisScore> diagnosisScores = new ArrayList<>();
        try {
            List<CurrencyInfo> currencyInfos = redisCacheComponent.getDiagnosisCurrencyList();
            if(currencyInfos==null || currencyInfos.size()==0){
                throw new ErrorDataException("查询CurrencyInfo失败!");
            }
            for (CurrencyInfo currencyInfo:currencyInfos) {
                if(currencyInfo.getCurrencyDiagnosisFlag()==null || !currencyInfo.getCurrencyDiagnosisFlag()){
                    continue;
                }
                try {
                    DiagnosisScore diagnosisScore = new DiagnosisScore();
                    diagnosisScore.setId(currencyInfo.getCmcId());

                    BigDecimal diagnosisScoreDecimal = new BigDecimal(0);

                    if(googleTrends!=null){
                        for (TrendsInfo t:googleTrends) {
                            if(StringUtils.equals(t.getId(),currencyInfo.getCmcId())){
                                if(t.getScore()!=null){
                                    diagnosisScoreDecimal =
                                            diagnosisScoreDecimal.add(t.getScore().multiply(new BigDecimal(0.15)));
                                }
                                diagnosisScore.setTrendsInfoScore(t.getScore());
                                diagnosisScore.setTrendsInfoResult(t.getResult());
                                break;
                            }
                        }
                    }
                    if(liquidities!=null){
                        for (Liquidity l:liquidities) {
                            if(StringUtils.equals(l.getId(),currencyInfo.getCmcId())){
                                if(l.getCreateTime()!=null && diagnosisScore.getCreateTime()==null){
                                    diagnosisScore.setCreateTime(l.getCreateTime());
                                    diagnosisScore.setMinute(DateUtils.dateToLocalDateTime(l.getCreateTime()).getMinute());
                                }
                                if(l.getScore()!=null){
                                    diagnosisScoreDecimal =
                                            diagnosisScoreDecimal.add(new BigDecimal(l.getScore()).multiply(new BigDecimal(0.2)));
                                    diagnosisScore.setLiquidityComment(l.getComment());
                                    diagnosisScore.setLiquidityScore(l.getScore());
                                }
                                break;
                            }
                        }

                    }

                    if(popularityIndicatorMap!=null){
                        PopularityIndicator popularityIndicator = popularityIndicatorMap.get(currencyInfo.getCmcId());
                        if(popularityIndicator!=null && popularityIndicator.getScore()!=null){
                            if(diagnosisScore.getCreateTime()==null){
                                diagnosisScore.setCreateTime(popularityIndicator.getCreateTime());
                                diagnosisScore.setMinute(DateUtils.dateToLocalDateTime(popularityIndicator.getCreateTime()).getMinute());
                            }
                            if(popularityIndicator.getScore()!=null){
                                diagnosisScoreDecimal =
                                        diagnosisScoreDecimal.add(new BigDecimal(popularityIndicator.getScore()).multiply(new BigDecimal(0.3)));
                                diagnosisScore.setPopularityIndicatorScore(popularityIndicator.getScore());
                                diagnosisScore.setPopularityIndicatorComment(popularityIndicator.getComment());
                            }
                        }
                    }

                    if(diagnosisQuantumEnergies!=null){
                        for (DiagnosisQuantumEnergy q:diagnosisQuantumEnergies) {
                            if(StringUtils.equals(currencyInfo.getCmcId(),q.getId())){
                                if(q.getScore()!=null){
                                    diagnosisScoreDecimal =
                                            diagnosisScoreDecimal.add(new BigDecimal(q.getScore()).multiply(new BigDecimal(0.3)));
                                }
                                if(diagnosisScore.getCreateTime()==null){
                                    diagnosisScore.setCreateTime(q.getCreateTime());
                                    diagnosisScore.setMinute(DateUtils.dateToLocalDateTime(q.getCreateTime()).getMinute());
                                }
                                diagnosisScore.setQuantumEnergyComment(q.getComment());
                                diagnosisScore.setQuantumEnergyScore(q.getScore());
                                break;
                            }
                        }

                    }

                    diagnosisScore.setDiagnosisScore(diagnosisScoreDecimal);
                    diagnosisScores.add(diagnosisScore);

                } catch (Exception e) {
                    e.printStackTrace();
                    LogTrace.error(e.getMessage(), e);
                }
            }
        } catch (ErrorDataException e) {
            e.printStackTrace();
            LogTrace.error(e.getMessage(), e);
        }
        if(CollectionUtil.isNotBlank(diagnosisScores)){
            for (DiagnosisScore diagnosisScore1:diagnosisScores) {
                int defect = 0;
                if(diagnosisScore1.getDiagnosisScore()==null){
                    continue;
                }
                for (DiagnosisScore diagnosisScore2:diagnosisScores) {
                    if(diagnosisScore2.getDiagnosisScore()!=null
                            && diagnosisScore1.getDiagnosisScore().doubleValue()>diagnosisScore2.getDiagnosisScore().doubleValue() ){
                        defect++;
                    }
                }
                diagnosisScore1.setDefect(
                        defect==0?new BigDecimal(0):( new BigDecimal(defect)
                                .divide(new BigDecimal(diagnosisScores.size()),4,BigDecimal.ROUND_DOWN)
                        )
                );

            }
            diagnosisScores.sort((DiagnosisScore d1,DiagnosisScore d2)->{
                if (d1.getDiagnosisScore()==null && d2.getDiagnosisScore()==null) {
                    return 0;
                } else if (d1.getDiagnosisScore()==null) {
                    return 1;
                } else if (d2.getDiagnosisScore()==null) {
                    return -1;
                }
                return d2.getDiagnosisScore().compareTo(d1.getDiagnosisScore());
            });
            List<DiagnosisScore> five = new ArrayList<>();
            for (int i = 0; i < (diagnosisScores.size()<8?diagnosisScores.size():8); i++) {
                five.add(diagnosisScores.get(i));
            }
            redisServer.set(RedisKeysUtils.DIAGNOSIS_SCORE_RANK,five);
        }

        return diagnosisScores;

    }

    /**
     * 保存货币诊断得分
     * @param diagnosisScores
     */
    public void saveDiagnosisScores(List<DiagnosisScore> diagnosisScores) {
        if(CollectionUtils.isEmpty(diagnosisScores)){
            return;
        }
        for (DiagnosisScore diagnosisScore:diagnosisScores) {
            try {
                String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.CURRENCY_DIAGNOSIS_SCORE_TABLE_NAME
                        , HbaseTableUtils.CURRENCY_DIAGNOSIS_SCORE_TABLE_FAMILY
                        , HbaseTableUtils.CURRENCY_DIAGNOSIS_SCORE_QUALIFIER
                        , diagnosisScore.getId()+"@"+DateUtils.getCurrentDateString());
                JSONObject mainObject;
                if(StringUtils.isBlank(data)){
                    mainObject = new JSONObject();
                }else{
                    mainObject = JSON.parseObject(data);
                }
                Date createTime = diagnosisScore.getCreateTime();
                if(createTime ==null){
                    createTime = new Date();
                }
                String key = DateUtils.dateToLocalDateTime(createTime).getHour()+"";
                JSONArray jsonArray = mainObject.getJSONArray(key);
                if(jsonArray==null){
                    jsonArray = new JSONArray();
                }
                jsonArray.add(diagnosisScore);
                mainObject.put(key,jsonArray);
                currencyInfoHbaseComponent.insertHbaseString(HbaseTableUtils.CURRENCY_DIAGNOSIS_SCORE_TABLE_NAME
                        ,diagnosisScore.getId()+"@"+DateUtils.getCurrentDateString()
                        ,HbaseTableUtils.CURRENCY_DIAGNOSIS_SCORE_TABLE_FAMILY
                        ,HbaseTableUtils.CURRENCY_DIAGNOSIS_SCORE_QUALIFIER
                        ,mainObject.toJSONString());

                HttpUtils.getAkka(akkaCurrencyDiagnosisAssessmentUrl);
                HttpUtils.getAkka(getMonetarydiagnosisTop5URL);
            } catch (HbaseConnectionExcetion|HbaseGetTableExcetion|IOException|HbaseCloseExcetion e) {
                e.printStackTrace();
                LogTrace.error(e.getMessage(), e);
            }
        }

    }


    /**
     * 多空趋势计算
     * @param cmcCurrencyInfoMap
     * @return
     */
    public List<LongShortTrend> calculateLongShortTrend(Map<String, CmcCurrencyInfo> cmcCurrencyInfoMap) {
        List<CurrencyInfo> currencyInfos = redisCacheComponent.getCurrencyList();
        if(CollectionUtil.isBlank(currencyInfos)){
            return null;
        }
        List<LongShortTrend> longShortTrends = new ArrayList<>();


        for (CurrencyInfo currencyInfo:currencyInfos) {
            CmcCurrencyInfo info = cmcCurrencyInfoMap.get(currencyInfo.getCmcId());
            if(info==null){
                continue;
            }
            try {
                LocalDateTime dateTime = DateUtils.dateToLocalDateTime(info.getCreateTime());
                Map<String, List<DailyComprehensiveAnalysisInfo>> dailyCurrencyInfor =
                        coinMarketCapDataComponent.getDailyCurrencyInfor(
                                currencyInfo.getCmcId()+"@"+DateUtils.dateFormatString(info.getCreateTime(),DateUtils.format_ymds));
                Map<String, List<DailyComprehensiveAnalysisInfo>> yesterdayCurrencyInfor =
                        coinMarketCapDataComponent.getDailyCurrencyInfor(
                                currencyInfo.getCmcId()+"@"+DateUtils.dateFormatString(
                                        DateUtils.localDateTimeToDate(dateTime.minusDays(1)),DateUtils.format_ymds));
                if(CollectionUtil.isBlank(dailyCurrencyInfor)){
                    continue;
                }
                BigDecimal sum1Price = new BigDecimal(0);
                BigDecimal sum2Price = new BigDecimal(0);
                int size1 = 0;
                int size2 = 0;
                for (int i = 0; i < 24; i++) {
                    LocalDateTime minusHoursTime = dateTime.minusHours(i);
                    List<DailyComprehensiveAnalysisInfo> list;
                    if(dateTime.getDayOfYear()!=minusHoursTime.getDayOfYear()){
                        list = yesterdayCurrencyInfor.get(minusHoursTime.getHour() + "");
                    }else{
                        list = dailyCurrencyInfor.get(minusHoursTime.getHour() + "");
                    }
                    if(CollectionUtil.isBlank(list)){
                        continue;
                    }
                    for (DailyComprehensiveAnalysisInfo daily:list) {
                        if(MathUtils.isNumeric(daily.getPriceCny())){
                            if(i<5){
                                sum1Price = sum1Price.add(new BigDecimal(daily.getPriceCny()));
                                size1++;
                            }
                            sum2Price = sum2Price.add(new BigDecimal(daily.getPriceCny()));
                            size2++;
                        }
                    }
                }

                LongShortTrend longShortTrend = new LongShortTrend();
                longShortTrend.setId(info.getId());
                longShortTrend.setCreateTime(info.getCreateTime());
                longShortTrend.setMinute(DateUtils.dateToLocalDateTime(info.getCreateTime()).getMinute());
                if(MathUtils.isNotNumeric(info.getPriceCny())){
                    continue;
                }
                BigDecimal price = new BigDecimal(info.getPriceCny());
                BigDecimal avg1Price = sum1Price.divide(new BigDecimal(size1),2,BigDecimal.ROUND_DOWN);
                BigDecimal avg2Price = sum2Price.divide(new BigDecimal(size2),2,BigDecimal.ROUND_DOWN);
                longShortTrend.setPriceCny(price);
                longShortTrend.setAvg1PriceCny(avg1Price);
                longShortTrend.setAvg2PriceCny(avg2Price);
                /*List<DailyComprehensiveAnalysisInfo> oneHoursInfoHbases = dailyCurrencyInfor.get(dateTime.minusHours(1).getHour()+"");
                BigDecimal price = new BigDecimal(info.getPriceCny());
                longShortTrend.setPriceCny(price);
                BigDecimal sumOneHoursPrice = new BigDecimal(0);
                int oneHoursSize = oneHoursInfoHbases.size();
                for (DailyComprehensiveAnalysisInfo infoHbase:oneHoursInfoHbases) {
                    if(MathUtils.isNumeric(infoHbase.getPriceCny())){
                        sumOneHoursPrice = sumOneHoursPrice.add(new BigDecimal(infoHbase.getPriceCny()));
                    }

                }
                BigDecimal avgOneHoursPrice = sumOneHoursPrice.divide(new BigDecimal(oneHoursSize),2,BigDecimal.ROUND_DOWN);
                longShortTrend.setAvgOneHoursPriceCny(avgOneHoursPrice);

                List<DailyComprehensiveAnalysisInfo> threeHoursInfoHbases = dailyCurrencyInfor.get(dateTime.minusHours(3).getHour()+"");
                BigDecimal sumThreeHoursPrice = new BigDecimal(0);
                int threeHoursSize = threeHoursInfoHbases.size();
                for (DailyComprehensiveAnalysisInfo infoHbase:threeHoursInfoHbases) {
                    if(MathUtils.isNumeric(infoHbase.getPriceCny())){
                        sumThreeHoursPrice = sumThreeHoursPrice.add(new BigDecimal(infoHbase.getPriceCny()));
                    }

                }
                BigDecimal avgThreeHoursPrice = sumThreeHoursPrice.divide(new BigDecimal(threeHoursSize),2,BigDecimal.ROUND_DOWN);
                longShortTrend.setAvgThreeHoursPriceCny(avgThreeHoursPrice);
*/

                if(price.doubleValue()>avg1Price.doubleValue()
                        && price.doubleValue()>avg2Price.doubleValue()){
                    longShortTrend.setComment("短期行情较为强势");
                }else if(
                        (price.doubleValue()<=avg1Price.doubleValue()
                                && price.doubleValue()>=avg2Price.doubleValue())
                                ||  (price.doubleValue()>=avg1Price.doubleValue()
                                && price.doubleValue()<=avg2Price.doubleValue())
                        ){
                    longShortTrend.setComment("短期行情盘整");
                }else if(price.doubleValue()<avg1Price.doubleValue()
                        && price.doubleValue()<avg2Price.doubleValue()){
                    longShortTrend.setComment("短期行情较为弱势");
                }
                longShortTrends.add(longShortTrend);

            } catch (Exception e) {
                e.printStackTrace();
                LogTrace.error(e.getMessage(), e);
            }

        }
        return longShortTrends;
    }


    /**
     * 保存多空趋势
     * @param longShortTrends
     */
    public void saveLongShortTrend(List<LongShortTrend> longShortTrends) {
        for (LongShortTrend longShortTrend:longShortTrends) {
            try {
                String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.LONG_AND_SHORT_TREND_TABLE_NAME
                        , HbaseTableUtils.LONG_AND_SHORT_TREND_TABLE_NAME_FAMILY
                        , HbaseTableUtils.LONG_AND_SHORT_TREND_TABLE_NAME_QUALIFIER
                        , longShortTrend.getId()+"@"+DateUtils.getCurrentDateString());
                JSONObject mainObject;
                if(StringUtils.isBlank(data)){
                    mainObject = new JSONObject();
                }else{
                    mainObject = JSON.parseObject(data);
                }
                String key = DateUtils.dateToLocalDateTime(longShortTrend.getCreateTime()).getHour()+"";
                JSONArray jsonArray = mainObject.getJSONArray(key);
                if(jsonArray==null){
                    jsonArray = new JSONArray();
                }
                jsonArray.add(longShortTrend);
                mainObject.put(key,jsonArray);
                currencyInfoHbaseComponent.insertHbaseString(HbaseTableUtils.LONG_AND_SHORT_TREND_TABLE_NAME
                        ,longShortTrend.getId()+"@"+DateUtils.getCurrentDateString()
                        ,HbaseTableUtils.LONG_AND_SHORT_TREND_TABLE_NAME_FAMILY
                        ,HbaseTableUtils.LONG_AND_SHORT_TREND_TABLE_NAME_QUALIFIER
                        ,mainObject.toJSONString());

                HttpUtils.getAkka(getSpaceTrendURL);

            } catch (Exception e) {
                e.printStackTrace();
                LogTrace.error(e.getMessage(), e);
            }
        }


    }

    /**
     * 计算平均成本
     * @param cmcInfosMap
     * @param currencies
     * @return
     */
    public List<DiagnosisAverageCost> calculateDiagnosisAverageCost(Map<String,CmcCurrencyInfo> cmcInfosMap, Map<String, List<CurrencyHistorical>> currencies) {
        List<CurrencyInfo> currencyInfos = redisCacheComponent.getNotNullFixedTurnoverRateCurrencyList();
        List<DiagnosisAverageCost> diagnosisAverageCosts = new ArrayList<>();
        for (CurrencyInfo currencyInfo:currencyInfos) {
            try {

                DiagnosisAverageCost diagnosisAverageCost = new DiagnosisAverageCost();
                diagnosisAverageCost.setId(currencyInfo.getCmcId());
                //List<CurrencyHistorical> currencyHistoricals = currencies.get(currencyInfo.getCmcId());
                Map<String, List<DailyComprehensiveAnalysisInfo>> dailyMap
                        = coinMarketCapDataComponent.getDailyCurrencyInfor(
                                currencyInfo.getCmcId() + "@" + DateUtils.getCurrentDateString());
                if(CollectionUtil.isBlank(dailyMap)){
                    throw new ErrorDataException("获取货币历史数据失败！"+currencyInfo.getCmcId());
                }
                CmcCurrencyInfo cmcInfo = cmcInfosMap.get(currencyInfo.getCmcId());
                if(cmcInfo==null){
                    throw new ErrorDataException("获取货币当前货币数据失败！"+currencyInfo.getCmcId());
                }
                LocalDateTime dateTime = DateUtils.dateToLocalDateTime(cmcInfo.getCreateTime());
                diagnosisAverageCost.setCreateTime(cmcInfo.getCreateTime());
                diagnosisAverageCost.setMinute(dateTime.getMinute());
                List<DailyComprehensiveAnalysisInfo> dailyList = dailyMap.get(dateTime.minusHours(1).getHour() + "");
                if(CollectionUtil.isBlank(dailyList) || MathUtils.isNotNumeric(dailyList.get(dailyList.size()-1).getPriceCny())){
                    continue;
                }
                BigDecimal closingPrice = new BigDecimal(dailyList.get(dailyList.size()-1).getPriceCny());
                if(MathUtils.isNotNumeric(cmcInfo.getPriceCny())){
                    continue;
                }
                diagnosisAverageCost.setPriceCny(new BigDecimal(cmcInfo.getPriceCny()));
                BigDecimal price = new BigDecimal(cmcInfo.getPriceCny());
                BigDecimal fixedTurnoverRate =
                        new BigDecimal(currencyInfo.getFixedTurnoverRate()).multiply(new BigDecimal(0.01));
                diagnosisAverageCost.setDiagnosisAverageCost(
                        closingPrice.multiply(new BigDecimal(1).subtract(fixedTurnoverRate))
                                .add(fixedTurnoverRate.multiply(price))
                );
                double value = diagnosisAverageCost.getDiagnosisAverageCost().doubleValue();
                String format = String.format("%.2f", value);
                if(price.doubleValue()>= value){
                    diagnosisAverageCost.setComment("即时价格大于平均成本，近期投资者整体盈利");
                }else if(price.doubleValue()< value){
                    diagnosisAverageCost.setComment("即时价格小于平均成本，近期投资者整体亏损");
                }/*else{
                    diagnosisAverageCost.setComment("近期平均成本"+format+"元，价格等于平均成本");
                }*/
                diagnosisAverageCosts.add(diagnosisAverageCost);

            }  catch (ErrorDataException e) {
                e.printStackTrace();
                LogTrace.error(e.getMessage(), e);
            }

        }
        return diagnosisAverageCosts;
    }

    /**
     * 保存平均成本
     * @param diagnosisAverageCosts
     */
    public void saveDiagnosisAverageCost(List<DiagnosisAverageCost> diagnosisAverageCosts) {
        for (DiagnosisAverageCost diagnosisAverageCost:diagnosisAverageCosts) {
            try {
                String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.CURRENCY_DIAGNOSIS_AVERAGE_COST_INFO_TABLE_NAME
                        , HbaseTableUtils.CURRENCY_DIAGNOSIS_AVERAGE_COST_INFO_TABLE_FAMILY
                        , HbaseTableUtils.CURRENCY_DIAGNOSIS_AVERAGE_COST_INFO_QUALIFIER
                        , diagnosisAverageCost.getId()+"@"+DateUtils.getCurrentDateString());
                JSONObject mainObject;
                if(StringUtils.isBlank(data)){
                    mainObject = new JSONObject();
                }else{
                    mainObject = JSON.parseObject(data);
                }
                String key = DateUtils.dateToLocalDateTime(diagnosisAverageCost.getCreateTime()).getHour()+"";
                JSONArray jsonArray = mainObject.getJSONArray(key);
                if(jsonArray==null){
                    jsonArray = new JSONArray();
                }
                jsonArray.add(diagnosisAverageCost);
                mainObject.put(key,jsonArray);
                currencyInfoHbaseComponent.insertHbaseString(HbaseTableUtils.CURRENCY_DIAGNOSIS_AVERAGE_COST_INFO_TABLE_NAME
                        ,diagnosisAverageCost.getId()+"@"+DateUtils.getCurrentDateString()
                        ,HbaseTableUtils.CURRENCY_DIAGNOSIS_AVERAGE_COST_INFO_TABLE_FAMILY
                        ,HbaseTableUtils.CURRENCY_DIAGNOSIS_AVERAGE_COST_INFO_QUALIFIER
                        ,mainObject.toJSONString());

                HttpUtils.getAkka(getAvgCostURL);

            } catch (Exception e) {
                e.printStackTrace();
                LogTrace.error(e.getMessage(), e);
            }
        }

    }


    /**
     * 计算货币排名
     * @param cmcCurrencyInfos
     * @return
     */
    public CoinRank calculateCoinRank(List<CmcCurrencyInfo> cmcCurrencyInfos) {
        List<CurrencyInfo> currencyList = redisCacheComponent.getDiagnosisCurrencyList();
        List<CmcCurrencyInfo> enableInfos = new ArrayList<>();
        Map<String, CmcCurrencyInfo> infoMap = this.cmcCurrencyInfoListToMap(cmcCurrencyInfos);
        for (CurrencyInfo currencyInfo:currencyList) {
            CmcCurrencyInfo cmcCurrencyInfo = infoMap.get(currencyInfo.getCmcId());
            enableInfos.add(cmcCurrencyInfo);
        }
        CoinRank coinRank = new CoinRank();
        if(CollectionUtils.isNotEmpty(enableInfos)){
            enableInfos.sort((CmcCurrencyInfo c1, CmcCurrencyInfo c2) ->{
                if (MathUtils.isNotNumeric(c1.getMarketCapCny())
                        && MathUtils.isNotNumeric(c2.getMarketCapCny())) {
                    return 0;
                } else if (MathUtils.isNotNumeric(c1.getMarketCapCny())) {
                    return 1;
                } else if (MathUtils.isNotNumeric(c2.getMarketCapCny())) {
                    return -1;
                }
                BigDecimal c1BigDecimal = new BigDecimal(c1.getMarketCapCny());
                BigDecimal c2BigDecimal = new BigDecimal(c2.getMarketCapCny());
                return c2BigDecimal.compareTo(c1BigDecimal);
            });
            ArrayList<CmcCurrencyInfo> marketCapRankList = new ArrayList<>();
            for (int i = 0; i < (enableInfos.size()>20?20:enableInfos.size()); i++) {
                CmcCurrencyInfo info = enableInfos.get(i);
                marketCapRankList.add(info);
            }
            coinRank.setMarketCapRankList(marketCapRankList);
            enableInfos.sort((CmcCurrencyInfo c1, CmcCurrencyInfo c2) ->{
                if (MathUtils.isNotNumeric(c1.getPercentChange24h())
                        && MathUtils.isNotNumeric(c2.getPercentChange24h())) {
                    return 0;
                } else if (MathUtils.isNotNumeric(c1.getPercentChange24h())) {
                    return 1;
                } else if (MathUtils.isNotNumeric(c2.getPercentChange24h())) {
                    return -1;
                }
                BigDecimal c1BigDecimal = new BigDecimal(c1.getPercentChange24h());
                BigDecimal c2BigDecimal = new BigDecimal(c2.getPercentChange24h());
                return c2BigDecimal.compareTo(c1BigDecimal);
            });
            ArrayList<CmcCurrencyInfo> percentChangeRankList = new ArrayList<>();
            for (int i = 0; i < (enableInfos.size()>20?20:enableInfos.size()); i++) {
                CmcCurrencyInfo info = enableInfos.get(i);
                percentChangeRankList.add(info);
            }
            coinRank.setPercentChangeRankList(percentChangeRankList);
            enableInfos.sort((CmcCurrencyInfo c1, CmcCurrencyInfo c2) ->{
                if (MathUtils.isNotNumeric(c1.getVolume24hCny())
                        && MathUtils.isNotNumeric(c2.getVolume24hCny())) {
                    return 0;
                } else if (MathUtils.isNotNumeric(c1.getVolume24hCny())) {
                    return 1;
                } else if (MathUtils.isNotNumeric(c2.getVolume24hCny())) {
                    return -1;
                }
                BigDecimal c1BigDecimal = new BigDecimal(c1.getVolume24hCny());
                BigDecimal c2BigDecimal = new BigDecimal(c2.getVolume24hCny());
                return c2BigDecimal.compareTo(c1BigDecimal);
            });
            ArrayList<CmcCurrencyInfo> volumeRankList = new ArrayList<>();
            for (int i = 0; i < (enableInfos.size()>20?20:enableInfos.size()); i++) {
                CmcCurrencyInfo info = enableInfos.get(i);
                volumeRankList.add(info);
            }
            coinRank.setVolumeRankList(volumeRankList);
        }

        redisServer.set(RedisKeysUtils.COIN_RANK,coinRank);
        currencyInfoHbaseComponent.insertHbaseString(HbaseTableUtils.LEADERBOARD_TABLE_NAME
                ,DateUtils.getCurrentDateString()
                ,HbaseTableUtils.LEADERBOARD_TABLE_NAME_FAMILY
                ,HbaseTableUtils.LEADERBOARD_QUALIFIER
                ,JSON.toJSONString(coinRank));
        return coinRank;
    }


    /**
     * 计算基期权重
     * @return
     * @throws ErrorDataException
     */
    public BigDecimal calculateBasePeriodWeightIndex() throws ErrorDataException {
        BigDecimal basePeriod = null;
        List<CurrencyInfo> currencyInfos = redisCacheComponent.getWeightsCurrencyList();
        if(CollectionUtils.isEmpty(currencyInfos)){
            throw new ErrorDataException("计算权重指数获取权重信息失败！");
        }
        if("0".equals(redisServer.get(RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD))){
            String valueString = redisServer.get(RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD_VALUE);
            if(MathUtils.isNumeric(valueString)){
                basePeriod = new BigDecimal(valueString);
            }else{
                BasePeriodHistory basePeriodHistory = new BasePeriodHistory();
                basePeriodHistory.setBasePeriodMark(BasePeriodMarkEnum.WEIGHT_INDEX.getIndex());
                basePeriodHistory = basePeriodHistoryService.selectByEntity(basePeriodHistory);
                if(basePeriodHistory!=null && basePeriodHistory.getBasePeriod()!=null){
                    basePeriod = basePeriodHistory.getBasePeriod();
                }
            }
        }
        if(basePeriod==null){
            Date baseTime = null;
            for (CurrencyInfo currencyInfo:currencyInfos) {
                    if(currencyInfo.getUpdateTime()!=null){
                        baseTime = currencyInfo.getUpdateTime();
                    }else{
                        baseTime = currencyInfo.getCreateTime();
                    }
                    if(currencyInfo.getUpdateTime()!=null
                            && currencyInfo.getUpdateTime().getTime()>baseTime.getTime()){
                        baseTime = currencyInfo.getUpdateTime();
                    }else if(currencyInfo.getCreateTime()!=null
                            && currencyInfo.getCreateTime().getTime()>baseTime.getTime()){
                        baseTime = currencyInfo.getCreateTime();
                    }
            }
            List<CmcCurrencyInfo> firstCmcInfos = coinMarketCapDataComponent.getCmcInfosByDate(baseTime);
            if(CollectionUtils.isEmpty(firstCmcInfos)){
                throw new ErrorDataException("基期货币信息获取失败！"+baseTime);
            }
            Map<String, CmcCurrencyInfo> firstCmcMap = this.cmcCurrencyInfoListToMap(firstCmcInfos);
            if(CollectionUtil.isNotBlank(firstCmcMap)){
                basePeriod = new BigDecimal(0);
                for (CurrencyInfo currencyInfo:currencyInfos) {
                    CmcCurrencyInfo cmcInfo = firstCmcMap.get(currencyInfo.getCmcId());
                    if(cmcInfo!=null){
                        BigDecimal price = new BigDecimal(cmcInfo.getPriceCny());
                        BigDecimal availableSupply = new BigDecimal(cmcInfo.getAvailableSupply());
                        basePeriod =
                                basePeriod.add(price.multiply(availableSupply));
                    }
                }
                BasePeriodHistory basePeriodHistory = new BasePeriodHistory();
                basePeriodHistory.setBasePeriodMark(BasePeriodMarkEnum.WEIGHT_INDEX.getIndex());
                basePeriodHistory.setBasePeriod(basePeriod);
                basePeriodHistory.setConceptIndustryCurrencyId(0);
                basePeriodHistoryService.insertSelective(basePeriodHistory);
                redisServer.set(RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD,"0");
                redisServer.set(RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD_VALUE,basePeriod.doubleValue());
            }
        }

        return basePeriod;
    }


    /**
     * 计算权重基期
     * @return
     * @throws ErrorDataException
     */
    public void calculateBasePeriodWeightIndexNew() throws ErrorDataException {
        if("1".equals(redisServer.get(RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD))){

            //计算基期市值之和
            String CURRCY_WEIGHTS_BASE_PERIOD_VALUE = redisServer.get(RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD_VALUE);
            if(StringUtils.isBlank( CURRCY_WEIGHTS_BASE_PERIOD_VALUE ) || Double.parseDouble( CURRCY_WEIGHTS_BASE_PERIOD_VALUE )==0){
                LogTrace.info("calculateBasePeriodWeightIndexNew" , "calculateBasePeriodWeightIndexNew" , "weights IsNull!");
                List<CurrencyInfo> currencyInfos = redisCacheComponent.getWeightsCurrencyList();
                if(CollectionUtils.isEmpty(currencyInfos)){
                    throw new ErrorDataException("计算权重指数获取权重信息失败！");
                }
                Date baseTime = null;
                for (CurrencyInfo currencyInfo:currencyInfos) {
                    if(currencyInfo.getUpdateTime()!=null){
                        baseTime = currencyInfo.getUpdateTime();
                    }else{
                        baseTime = currencyInfo.getCreateTime();
                    }
                    if(currencyInfo.getUpdateTime()!=null
                            && currencyInfo.getUpdateTime().getTime()>baseTime.getTime()){
                        baseTime = currencyInfo.getUpdateTime();
                    }else if(currencyInfo.getCreateTime()!=null
                            && currencyInfo.getCreateTime().getTime()>baseTime.getTime()){
                        baseTime = currencyInfo.getCreateTime();
                    }
                }
                List<CmcCurrencyInfo> firstCmcInfos = coinMarketCapDataComponent.getCmcInfosByDate(baseTime);
                if(CollectionUtils.isEmpty(firstCmcInfos)){
                    throw new ErrorDataException("基期货币信息获取失败！"+baseTime);
                }
                Map<String, CmcCurrencyInfo> firstCmcMap = this.cmcCurrencyInfoListToMap(firstCmcInfos);
                if(CollectionUtil.isNotBlank(firstCmcMap)){
                    BigDecimal marketCapUsd = new BigDecimal( 0 );
                    for (CurrencyInfo currencyInfo:currencyInfos) {
                        CmcCurrencyInfo cmcInfo = firstCmcMap.get(currencyInfo.getCmcId());
                        if(cmcInfo!=null){
                            BigDecimal price = new BigDecimal(cmcInfo.getPriceCny());
                            BigDecimal availableSupply = new BigDecimal(cmcInfo.getAvailableSupply());
                            marketCapUsd = marketCapUsd.add(price.multiply(availableSupply));
                        }
                    }
                    redisServer.set(RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD_VALUE,StringUtil.getDoubleTwo( marketCapUsd.doubleValue( ) ) );
                }
            }

            //计算基期
            String CURRCY_WEIGHTS_BASE_PERIOD_QUANZHONG_VALUE = redisServer.get(RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD_QUANZHONG_VALUE);
            //基期为空按照旧公式算
            double weightsResult = 0;
            if(StringUtils.isBlank(CURRCY_WEIGHTS_BASE_PERIOD_QUANZHONG_VALUE) || Double.parseDouble( CURRCY_WEIGHTS_BASE_PERIOD_QUANZHONG_VALUE )==0){
                LogTrace.info("calculateBasePeriodWeightIndexNew" , "calculateBasePeriodWeightIndexNew" , "计算原基期");
                double marketCapCny = getMarketCapCny();
                String CURRCY_WEIGHTS_BASE_PERIOD_VALUE2 = redisServer.get(RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD_VALUE );
                if(StringUtils.isNotBlank( CURRCY_WEIGHTS_BASE_PERIOD_VALUE2 )){
                   double weights = Double.parseDouble( CURRCY_WEIGHTS_BASE_PERIOD_VALUE2 );
                   if(weights!=0){
                       weightsResult = marketCapCny*1000/weights;
                       redisServer.set(RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD_QUANZHONG_VALUE,StringUtil.getDoubleTwo( weightsResult ) );
                   }
                }
            }else{
                LogTrace.info("calculateBasePeriodWeightIndexNew" , "calculateBasePeriodWeightIndexNew" , "计算新基期");
                //基期不为空按照新公式算
                //最新市值之和
                double marketCapCny = getMarketCapCny();
                //原基期
                BigDecimal weightsQuan =null;
                //更改前的市值之和
                BigDecimal weights =null;

                String CURRCY_WEIGHTS_BASE_PERIOD_QUANZHONG_VALUE2 = redisServer.get( RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD_QUANZHONG_VALUE );
                if(StringUtils.isNotBlank( CURRCY_WEIGHTS_BASE_PERIOD_QUANZHONG_VALUE2 )){
                    weightsQuan = new BigDecimal( CURRCY_WEIGHTS_BASE_PERIOD_QUANZHONG_VALUE2 );
                }
                String CURRCY_WEIGHTS_BASE_PERIOD_VALUE3 = redisServer.get( RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD_VALUE );
                if(StringUtils.isNotBlank( CURRCY_WEIGHTS_BASE_PERIOD_VALUE3 )){
                    weights = new BigDecimal( CURRCY_WEIGHTS_BASE_PERIOD_VALUE3 );
                }
                if(BigDecimal.ZERO!=weights){
                    weightsResult = marketCapCny*weightsQuan.doubleValue()/weights.doubleValue();
                    redisServer.set(RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD_QUANZHONG_VALUE, StringUtil.getDoubleTwo( weightsResult ) );
                }
            }
            //基期入库
            MathContext mc = new MathContext(2, RoundingMode.HALF_DOWN);
            BasePeriodHistory basePeriodHistory = new BasePeriodHistory();
            basePeriodHistory.setBasePeriodMark( BasePeriodMarkEnum.WEIGHT_INDEX.getIndex() );
            basePeriodHistory.setCreateTime( new Date(  ) );
            basePeriodHistory.setBasePeriod( new BigDecimal( weightsResult ).setScale(2, BigDecimal.ROUND_HALF_UP) );
            basePeriodHistoryService.insertSelective( basePeriodHistory );
            redisServer.set(RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD,"0");
        }
    }

    //权重新的基期流通市值
    public double getMarketCapCny() throws ErrorDataException {
        //上币后的流通市值之和
        CurrencyInfo currencyInfo = new CurrencyInfo();
        currencyInfo.setEnableFlag( true );
        currencyInfo.setDeleteFlag( false );
        currencyInfo.setWeights( true );
        List<CurrencyInfo> currencyInfos = currencyInfoService.selectByEntityList( currencyInfo );
        if(CollectionUtils.isEmpty(currencyInfos)){
            return 0;
        }
        double marketCapCnyNew=0;
        for(int i=0;i<currencyInfos.size();i++){
             currencyInfo = currencyInfos.get( i );
            if(StringUtils.isNotBlank( currencyInfo.getCmcId() )){
                String redisCacheKey =  RedisKeysUtils.CURRENCY_MARKET+currencyInfo.getCmcId();
                String result=redisServer.get( redisCacheKey);
                if (result!=null){
                    CurrencyQuotationResultVo currencyQuotationResultVo = JSON.parseObject( result,CurrencyQuotationResultVo.class );
                    marketCapCnyNew=marketCapCnyNew+currencyQuotationResultVo.getMarketCapCny();
                }
            }
        }

        //上币前的流通市值之和
        double marketCapCnyOld=0;
        String WEIGHT_COEFFICIENT = redisServer.get( RedisKeysUtils.WEIGHT_COEFFICIENT );
        if(StringUtils.isNotBlank( WEIGHT_COEFFICIENT )){
            List<CurrencyInfo>  currencyInfoList = JSON.parseArray( WEIGHT_COEFFICIENT,CurrencyInfo.class );
            if(currencyInfoList.size()>0){
                List<CurrencyInfo> currencyInfos2 = currencyInfoList;
                for(int i=0;i<currencyInfos2.size();i++){
                    currencyInfo = currencyInfos2.get( i );
                    if(StringUtils.isNotBlank( currencyInfo.getCmcId() )){
                        String redisCacheKey =  RedisKeysUtils.CURRENCY_MARKET+currencyInfo.getCmcId();
                        String result=redisServer.get( redisCacheKey);
                        if (result!=null){
                            CurrencyQuotationResultVo currencyQuotationResultVo = JSON.parseObject( result,CurrencyQuotationResultVo.class );
                            marketCapCnyOld=marketCapCnyOld+currencyQuotationResultVo.getMarketCapCny();
                        }
                    }
                }
            }
        }

        //新的基期流通市值
        double result = 0;
        String CURRCY_WEIGHTS_BASE_PERIOD_VALUE = redisServer.get(RedisKeysUtils.CURRCY_WEIGHTS_BASE_PERIOD_VALUE);
        if(StringUtils.isNotBlank( CURRCY_WEIGHTS_BASE_PERIOD_VALUE )){
            if(marketCapCnyOld!=0){
                //新的基期流通市值=旧基期的流通市值之和x上币后的流通市值之和/上币前的流通市值之和
                result = Double.parseDouble( CURRCY_WEIGHTS_BASE_PERIOD_VALUE )*marketCapCnyNew/marketCapCnyOld;
            }
        }
        return result;
    }

    //获取行业货币最新市值之和
    public double getMarketCapCnyIndustry(int id) throws ErrorDataException {
        //上币后的流通市值之和
        CurrencyInfo currencyInfo = new CurrencyInfo();
        currencyInfo.setId( id );
        List<CurrencyInfo> currencyInfos = currencyInfoMapper.serchByCurrenByIncurrId(currencyInfo);
        if(CollectionUtils.isEmpty(currencyInfos)){
            return 0;
        }
        double marketCapCnyNew=0;
        for(int i=0;i<currencyInfos.size();i++){
             currencyInfo = currencyInfos.get( i );
            if(StringUtils.isNotBlank( currencyInfo.getCmcId() )){
                String redisCacheKey =  RedisKeysUtils.CURRENCY_MARKET+currencyInfo.getCmcId();
                String result=redisServer.get( redisCacheKey);
                if (result!=null){
                    CurrencyQuotationResultVo currencyQuotationResultVo = JSON.parseObject( result,CurrencyQuotationResultVo.class );
                    marketCapCnyNew=marketCapCnyNew+currencyQuotationResultVo.getMarketCapCny();
                }
            }
        }

        //上币前的流通市值之和
        double marketCapCnyOld=0;
        String INSTUDY_TRENDS = redisServer.get( RedisKeysUtils.INSTUDY_TRENDS+"@"+id );
        if(StringUtils.isNotBlank( INSTUDY_TRENDS )){
            List<CurrencyInfo>  currencyInfoList = JSON.parseArray( INSTUDY_TRENDS,CurrencyInfo.class );
            List<CurrencyInfo> currencyInfos2 = currencyInfoList;
            for(int i=0;i<currencyInfos2.size();i++){
                currencyInfo = currencyInfos2.get( i );
                if(StringUtils.isNotBlank( currencyInfo.getCmcId() )){
                    String redisCacheKey =  RedisKeysUtils.CURRENCY_MARKET+currencyInfo.getCmcId();
                    String result=redisServer.get( redisCacheKey);
                    if (result!=null){
                        CurrencyQuotationResultVo currencyQuotationResultVo = JSON.parseObject( result,CurrencyQuotationResultVo.class );
                        marketCapCnyOld=marketCapCnyOld+currencyQuotationResultVo.getMarketCapCny();
                    }
                }
            }
        }

        //新的基期流通市值
        double result = 0;
        String CURRCY_INDUSTRY_BASE_PERIOD_VALUE = redisServer.get(RedisKeysUtils.CURRCY_INDUSTRY_BASE_PERIOD_VALUE+id);
        if(StringUtils.isNotBlank( CURRCY_INDUSTRY_BASE_PERIOD_VALUE )){
            if(marketCapCnyOld!=0){
                result = Double.parseDouble( CURRCY_INDUSTRY_BASE_PERIOD_VALUE )*marketCapCnyNew/marketCapCnyOld;
            }}
        return result;
    }

    //获取概念货币最新市值之和
    public double getMarketCapCnyConcept(int id) throws ErrorDataException {
        //上币后的流通市值之和
        CurrencyInfo currencyInfo = new CurrencyInfo();
        currencyInfo.setId( id );
        List<CurrencyInfo> currencyInfos = currencyInfoMapper.serchByCurrentId(currencyInfo);
        if(CollectionUtils.isEmpty(currencyInfos)){
            return 0;
        }
        double marketCapCnyNew=0;
        for(int i=0;i<currencyInfos.size();i++){
             currencyInfo = currencyInfos.get( i );
            if(StringUtils.isNotBlank( currencyInfo.getCmcId() )){
                String redisCacheKey =  RedisKeysUtils.CURRENCY_MARKET+currencyInfo.getCmcId();
                String result=redisServer.get( redisCacheKey);
                if (result!=null){
                    CurrencyQuotationResultVo currencyQuotationResultVo = JSON.parseObject( result,CurrencyQuotationResultVo.class );
                    marketCapCnyNew=marketCapCnyNew+currencyQuotationResultVo.getMarketCapCny();
                }
            }
        }

        //上币前的流通市值之和
        double marketCapCnyOld=0;
        String CONCEPTION_HISTORY = redisServer.get( RedisKeysUtils.CONCEPTION_HISTORY+"@"+id );
        if(StringUtils.isNotBlank( CONCEPTION_HISTORY )){
            List<CurrencyInfo>  currencyInfoList = JSON.parseArray( CONCEPTION_HISTORY,CurrencyInfo.class );
            List<CurrencyInfo> currencyInfos2 = currencyInfoList;
            for(int i=0;i<currencyInfos2.size();i++){
                currencyInfo = currencyInfos2.get( i );
                if(StringUtils.isNotBlank( currencyInfo.getCmcId() )){
                    String redisCacheKey =  RedisKeysUtils.CURRENCY_MARKET+currencyInfo.getCmcId();
                    String result=redisServer.get( redisCacheKey);
                    if (result!=null){
                        CurrencyQuotationResultVo currencyQuotationResultVo = JSON.parseObject( result,CurrencyQuotationResultVo.class );
                        marketCapCnyOld=marketCapCnyOld+currencyQuotationResultVo.getMarketCapCny();
                    }
                }
            }
        }

        //新的基期流通市值
        double result = 0;
        String CURRCY_CONCEPT_BASE_PERIOD_VALUE = redisServer.get(RedisKeysUtils.CURRCY_CONCEPT_BASE_PERIOD_VALUE+id);
        if(StringUtils.isNotBlank( CURRCY_CONCEPT_BASE_PERIOD_VALUE )){
            if(marketCapCnyOld!=0){
                result = Double.parseDouble( CURRCY_CONCEPT_BASE_PERIOD_VALUE )*marketCapCnyNew/marketCapCnyOld;
            }}
        return result;
    }

    /**
     * 计算行业基期
     *
     * @param parentIndustryCategory
     * @return
     */
    public BigDecimal calculateBasePeriodindustry(CurrencyIndustryCategory parentIndustryCategory) {
        BigDecimal basePeriod = null;
        Integer id = parentIndustryCategory.getId();
        if("0".equals(redisServer.get(RedisKeysUtils.CURRCY_INDUSTRY_BASE_PERIOD + id))){
            String valueString = redisServer.get(RedisKeysUtils.CURRCY_INDUSTRY_BASE_PERIOD_VALUE + id);
            if(MathUtils.isNumeric(valueString)){
                basePeriod = new BigDecimal(valueString);
            }else{
                BasePeriodHistory basePeriodHistory = new BasePeriodHistory();
                basePeriodHistory.setBasePeriodMark(BasePeriodMarkEnum.INDUSTRY_INDEX.getIndex());
                basePeriodHistory = basePeriodHistoryService.selectByEntity(basePeriodHistory);
                if(basePeriodHistory!=null && basePeriodHistory.getBasePeriod()!=null){
                    basePeriod = basePeriodHistory.getBasePeriod();
                }
            }
        }
        if(basePeriod==null){
            //Date minCreateTime = redisCacheComponent.getCurrencyInfoHbaseMinCreateTime();
            CurrencyIndustryCategory searchIndustryCategory = new CurrencyIndustryCategory();
            searchIndustryCategory.setEnableFlag(true);
            List<CurrencyIndustryCategory> all = currencyIndustryCategoryService.selectByEntityList(searchIndustryCategory);
            List<CurrencyIndustryCategory> currencyIndustryCategories =
                    this.searchAllSonCurrencyIndustryCategory(parentIndustryCategory,all);
            if(CollectionUtil.isNotBlank(currencyIndustryCategories)){
                Date baseTime = null;
                for (CurrencyIndustryCategory industry:currencyIndustryCategories) {
                    CurrencyIndustryMiddle searchMiddle = new CurrencyIndustryMiddle();
                    searchMiddle.setIndustryCategoryId(industry.getId());
                    List<CurrencyIndustryMiddle> currencyIndustryMiddles = currencyIndustryMiddleService.selectByEntityList(searchMiddle);
                    if(CollectionUtil.isBlank(currencyIndustryMiddles)){
                        continue;
                    }
                    for (CurrencyIndustryMiddle middle:currencyIndustryMiddles) {
                        CurrencyInfo currencyInfo = currencyInfoService.selectByPrimaryKey(middle.getCurrencyId());
                        if(currencyInfo==null){
                            continue;
                        }
                        if(baseTime==null){
                            if(currencyInfo.getUpdateTime()!=null){
                                baseTime = currencyInfo.getUpdateTime();
                            }else{
                                baseTime = currencyInfo.getCreateTime();
                            }
                        }else{
                            if(currencyInfo.getUpdateTime()!=null
                                    && currencyInfo.getUpdateTime().getTime()>baseTime.getTime()){
                                baseTime = currencyInfo.getUpdateTime();
                            }else if(currencyInfo.getCreateTime()!=null
                                    && currencyInfo.getCreateTime().getTime()>baseTime.getTime()){
                                baseTime = currencyInfo.getCreateTime();
                            }
                        }
                    }

                }
                if(baseTime!=null){
                    List<CmcCurrencyInfo> minCmcInfos = coinMarketCapDataComponent.getCmcInfosByDate(baseTime);
                    basePeriod = this.sumIndustryPrice(parentIndustryCategory, minCmcInfos);
                    BasePeriodHistory basePeriodHistory = new BasePeriodHistory();
                    basePeriodHistory.setBasePeriodMark(BasePeriodMarkEnum.INDUSTRY_INDEX.getIndex());
                    basePeriodHistory.setBasePeriod(basePeriod);
                    basePeriodHistory.setConceptIndustryCurrencyId(id);
                    basePeriodHistoryService.insertSelective(basePeriodHistory);
                    redisServer.set(RedisKeysUtils.CURRCY_INDUSTRY_BASE_PERIOD + id,"0");
                    redisServer.set(RedisKeysUtils.CURRCY_INDUSTRY_BASE_PERIOD_VALUE + id,basePeriod.doubleValue());
                }
            }
        }
        return basePeriod;
    }


    /**
     * 计算行业基期
     *
     * @param parentIndustryCategory
     * @return7
     */
    public void calculateBasePeriodindustryNew(CurrencyIndustryCategory parentIndustryCategory) throws ErrorDataException {
        Integer id = parentIndustryCategory.getId();
        if("1".equals(redisServer.get(RedisKeysUtils.CURRCY_INDUSTRY_BASE_jiqi_PERIOD+id))){

            //计算行业基期市值之和
            String CURRCY_INDUSTRY_BASE_PERIOD_VALUE = redisServer.get(RedisKeysUtils.CURRCY_INDUSTRY_BASE_PERIOD_VALUE+id);
            if(StringUtils.isBlank( CURRCY_INDUSTRY_BASE_PERIOD_VALUE ) || Double.parseDouble( CURRCY_INDUSTRY_BASE_PERIOD_VALUE )==0 ){
                LogTrace.info("calculateBasePeriodindustryNew" , "calculateBasePeriodindustryNew" , "weights IsNull!");
                CurrencyInfo currencyInfo1 = new CurrencyInfo();
                currencyInfo1.setId( id );
                List<CurrencyInfo> currencyInfos = currencyInfoMapper.serchByCurrenByIncurrId(currencyInfo1);
                if(CollectionUtils.isEmpty(currencyInfos)){
                    return;
                }
                Date baseTime = null;
                for (CurrencyInfo currencyInfo:currencyInfos) {
                    if(currencyInfo.getUpdateTime()!=null){
                        baseTime = currencyInfo.getUpdateTime();
                    }else{
                        baseTime = currencyInfo.getCreateTime();
                    }
                    if(currencyInfo.getUpdateTime()!=null
                            && currencyInfo.getUpdateTime().getTime()>baseTime.getTime()){
                        baseTime = currencyInfo.getUpdateTime();
                    }else if(currencyInfo.getCreateTime()!=null
                            && currencyInfo.getCreateTime().getTime()>baseTime.getTime()){
                        baseTime = currencyInfo.getCreateTime();
                    }
                }
                List<CmcCurrencyInfo> firstCmcInfos = coinMarketCapDataComponent.getCmcInfosByDate(baseTime);
                if(CollectionUtils.isEmpty(firstCmcInfos)){
                    throw new ErrorDataException("基期货币信息获取失败！"+baseTime);
                }
                Map<String, CmcCurrencyInfo> firstCmcMap = this.cmcCurrencyInfoListToMap(firstCmcInfos);
                if(CollectionUtil.isNotBlank(firstCmcMap)){
                    BigDecimal marketCapUsd = new BigDecimal( 0 );
                    for (CurrencyInfo currencyInfo:currencyInfos) {
                        CmcCurrencyInfo cmcInfo = firstCmcMap.get(currencyInfo.getCmcId());
                        if(cmcInfo!=null){
                            BigDecimal price = new BigDecimal(cmcInfo.getPriceCny());
                            BigDecimal availableSupply = new BigDecimal(cmcInfo.getAvailableSupply());
                            marketCapUsd = marketCapUsd.add(price.multiply(availableSupply));
                        }
                    }
                    redisServer.set(RedisKeysUtils.CURRCY_INDUSTRY_BASE_PERIOD_VALUE+id,StringUtil.getDoubleTwo( marketCapUsd.doubleValue()));
                }
            }

            //计算基期
            String CURRCY_INDUSTRY_BASE_PERIOD_HANGYE_VALUE = redisServer.get(RedisKeysUtils.CURRCY_INDUSTRY_BASE_PERIOD_HANGYE_VALUE+id);
            //基期为空按照旧公式算
            double weightsResult = 0;
            if(StringUtils.isBlank(CURRCY_INDUSTRY_BASE_PERIOD_HANGYE_VALUE) || Double.parseDouble( CURRCY_INDUSTRY_BASE_PERIOD_HANGYE_VALUE )==0){
                LogTrace.info("calculateBasePeriodindustryNew" , "calculateBasePeriodindustryNew" , "计算原基期");
                double marketCapCny = getMarketCapCnyIndustry(id);
                String CURRCY_INDUSTRY_BASE_PERIOD_VALUE2 = redisServer.get(RedisKeysUtils.CURRCY_INDUSTRY_BASE_PERIOD_VALUE+id );
                if(StringUtils.isNotBlank( CURRCY_INDUSTRY_BASE_PERIOD_VALUE2 )){
                    double weights = Double.parseDouble( CURRCY_INDUSTRY_BASE_PERIOD_VALUE2 );
                    if(weights!=0){
                        weightsResult = marketCapCny*1000/weights;
                        redisServer.set(RedisKeysUtils.CURRCY_INDUSTRY_BASE_PERIOD_HANGYE_VALUE+id,StringUtil.getDoubleTwo( weightsResult ) );
                    }
                }
            }else{
                LogTrace.info("calculateBasePeriodindustryNew" , "calculateBasePeriodindustryNew" , "计算新基期");
                //基期不为空按照新公式算
                //最新市值之和
                double marketCapCny = getMarketCapCnyIndustry(id);
                //原基期
                BigDecimal weightsHang =null;
                //更改前的市值之和
                BigDecimal weights =null;

                String CURRCY_INDUSTRY_BASE_PERIOD_HANGYE_VALUE2 = redisServer.get( RedisKeysUtils.CURRCY_INDUSTRY_BASE_PERIOD_HANGYE_VALUE+id );
                if(StringUtils.isNotBlank( CURRCY_INDUSTRY_BASE_PERIOD_HANGYE_VALUE2 )){
                    weightsHang = new BigDecimal( CURRCY_INDUSTRY_BASE_PERIOD_HANGYE_VALUE2 );
                }
                String CURRCY_INDUSTRY_BASE_PERIOD_VALUE3 = redisServer.get( RedisKeysUtils.CURRCY_INDUSTRY_BASE_PERIOD_VALUE+id );
                if(StringUtils.isNotBlank( CURRCY_INDUSTRY_BASE_PERIOD_VALUE3 )){
                    weights = new BigDecimal( CURRCY_INDUSTRY_BASE_PERIOD_VALUE3 );
                }
                if(BigDecimal.ZERO!=weights){
                    weightsResult = marketCapCny*weightsHang.doubleValue()/weights.doubleValue();
                    redisServer.set(RedisKeysUtils.CURRCY_INDUSTRY_BASE_PERIOD_HANGYE_VALUE+id,StringUtil.getDoubleTwo( weightsResult ) );
                }
            }
            //基期入库
            MathContext mc = new MathContext(2, RoundingMode.HALF_DOWN);
            BasePeriodHistory basePeriodHistory = new BasePeriodHistory();
            basePeriodHistory.setBasePeriodMark( BasePeriodMarkEnum.INDUSTRY_INDEX.getIndex() );
            basePeriodHistory.setConceptIndustryCurrencyId( id );
            basePeriodHistory.setCreateTime( new Date(  ) );
            basePeriodHistory.setBasePeriod( new BigDecimal( weightsResult ).setScale(2, BigDecimal.ROUND_HALF_UP) );
            basePeriodHistoryService.insertSelective( basePeriodHistory );
            redisServer.set(RedisKeysUtils.CURRCY_INDUSTRY_BASE_jiqi_PERIOD+id,"0");
        }

    }

    /**
     * 计算概念基期
     *
     * @param parentIndustryCategory
     * @return7
     */
    public void calculateBasePeriodConceptNew(ConceptCategory conceptCategory) throws ErrorDataException {
        Integer id = conceptCategory.getId();
        if("1".equals(redisServer.get(RedisKeysUtils.CURRCY_NOTION_BASE_jiqi_PERIOD+id))){

            //计算行业基期市值之和
            String CURRCY_CONCEPT_BASE_PERIOD_VALUE = redisServer.get(RedisKeysUtils.CURRCY_CONCEPT_BASE_PERIOD_VALUE+id);
            if(StringUtils.isBlank( CURRCY_CONCEPT_BASE_PERIOD_VALUE ) || Double.parseDouble( CURRCY_CONCEPT_BASE_PERIOD_VALUE )==0){
                LogTrace.info("calculateBasePeriodConceptNew" , "calculateBasePeriodConceptNew" , "weights IsNull!");
                CurrencyInfo currencyInfo1 = new CurrencyInfo();
                currencyInfo1.setId( id );
                List<CurrencyInfo> currencyInfos = currencyInfoMapper.serchByCurrentId(currencyInfo1);
                if(CollectionUtils.isEmpty(currencyInfos)){
                    return;
                }
                Date baseTime = null;
                for (CurrencyInfo currencyInfo:currencyInfos) {
                    if(currencyInfo.getUpdateTime()!=null){
                        baseTime = currencyInfo.getUpdateTime();
                    }else{
                        baseTime = currencyInfo.getCreateTime();
                    }
                    if(currencyInfo.getUpdateTime()!=null
                            && currencyInfo.getUpdateTime().getTime()>baseTime.getTime()){
                        baseTime = currencyInfo.getUpdateTime();
                    }else if(currencyInfo.getCreateTime()!=null
                            && currencyInfo.getCreateTime().getTime()>baseTime.getTime()){
                        baseTime = currencyInfo.getCreateTime();
                    }
                }
                List<CmcCurrencyInfo> firstCmcInfos = coinMarketCapDataComponent.getCmcInfosByDate(baseTime);
                if(CollectionUtils.isEmpty(firstCmcInfos)){
                    throw new ErrorDataException("基期货币信息获取失败！"+baseTime);
                }
                Map<String, CmcCurrencyInfo> firstCmcMap = this.cmcCurrencyInfoListToMap(firstCmcInfos);
                if(CollectionUtil.isNotBlank(firstCmcMap)){
                    BigDecimal marketCapUsd = new BigDecimal( 0 );
                    for (CurrencyInfo currencyInfo:currencyInfos) {
                        CmcCurrencyInfo cmcInfo = firstCmcMap.get(currencyInfo.getCmcId());
                        if(cmcInfo!=null){
                            BigDecimal price = new BigDecimal(cmcInfo.getPriceCny());
                            BigDecimal availableSupply = new BigDecimal(cmcInfo.getAvailableSupply());
                            marketCapUsd = marketCapUsd.add(price.multiply(availableSupply));
                        }
                    }
                    redisServer.set(RedisKeysUtils.CURRCY_CONCEPT_BASE_PERIOD_VALUE+id,StringUtil.getDoubleTwo( marketCapUsd.doubleValue() ) );
                }
            }

            //计算基期
            String CURRCY_CONCEPT_BASE_PERIOD_GAINIAN_VALUE = redisServer.get(RedisKeysUtils.CURRCY_CONCEPT_BASE_PERIOD_GAINIAN_VALUE+id);
            //基期为空按照旧公式算
            double weightsResult =0;
            if(StringUtils.isBlank(CURRCY_CONCEPT_BASE_PERIOD_GAINIAN_VALUE) || Double.parseDouble( CURRCY_CONCEPT_BASE_PERIOD_GAINIAN_VALUE )==0){
                LogTrace.info("calculateBasePeriodConceptNew" , "calculateBasePeriodConceptNew" , "计算原基期");
                double marketCapCny = getMarketCapCnyConcept(id);
                String CURRCY_CONCEPT_BASE_PERIOD_VALUE2 = redisServer.get(RedisKeysUtils.CURRCY_CONCEPT_BASE_PERIOD_VALUE+id );
                if(StringUtils.isNotBlank( CURRCY_CONCEPT_BASE_PERIOD_VALUE2 )){
                    double weights = Double.parseDouble( CURRCY_CONCEPT_BASE_PERIOD_VALUE2 );
                    if(weights!=0){
                        weightsResult = marketCapCny*1000/weights;
                        redisServer.set(RedisKeysUtils.CURRCY_CONCEPT_BASE_PERIOD_GAINIAN_VALUE+id,StringUtil.getDoubleTwo( weightsResult ));
                    }
                }
            }else{
                LogTrace.info("calculateBasePeriodConceptNew" , "calculateBasePeriodConceptNew" , "计算新基期");
                //基期不为空按照新公式算
                //最新市值之和
                double marketCapCny = getMarketCapCnyConcept(id);
                //原基期
                BigDecimal weightsGai =null;
                //更改前的市值之和
                BigDecimal weights =null;

                String CURRCY_CONCEPT_BASE_PERIOD_GAINIAN_VALUE2 = redisServer.get( RedisKeysUtils.CURRCY_CONCEPT_BASE_PERIOD_GAINIAN_VALUE+id );
                if(StringUtils.isNotBlank( CURRCY_CONCEPT_BASE_PERIOD_GAINIAN_VALUE2 )){
                    weightsGai = new BigDecimal( CURRCY_CONCEPT_BASE_PERIOD_GAINIAN_VALUE2 );
                }
                String CURRCY_CONCEPT_BASE_PERIOD_VALUE3 = redisServer.get( RedisKeysUtils.CURRCY_CONCEPT_BASE_PERIOD_VALUE+id );
                if(StringUtils.isNotBlank( CURRCY_CONCEPT_BASE_PERIOD_VALUE3 )){
                    weights = new BigDecimal( CURRCY_CONCEPT_BASE_PERIOD_VALUE3 );
                }
                if(BigDecimal.ZERO!=weights){
                    weightsResult = marketCapCny*weightsGai.doubleValue()/weights.doubleValue();
                    redisServer.set(RedisKeysUtils.CURRCY_CONCEPT_BASE_PERIOD_GAINIAN_VALUE+id,StringUtil.getDoubleTwo( weightsResult ) );
                }
            }
            //基期入库
            MathContext mc = new MathContext(2, RoundingMode.HALF_DOWN);
            BasePeriodHistory basePeriodHistory = new BasePeriodHistory();
            basePeriodHistory.setBasePeriodMark( BasePeriodMarkEnum.CONCEPT_INDEX.getIndex() );
            basePeriodHistory.setConceptIndustryCurrencyId( id );
            basePeriodHistory.setCreateTime( new Date(  ) );
            basePeriodHistory.setBasePeriod( new BigDecimal( weightsResult  ).setScale(2, BigDecimal.ROUND_HALF_UP) );
            basePeriodHistoryService.insertSelective( basePeriodHistory );
            redisServer.set(RedisKeysUtils.CURRCY_NOTION_BASE_jiqi_PERIOD+id,"0");
        }
    }
}
